标签导航:

spring boot jar包含多个启动类,如何指定启动哪个?

Spring Boot项目打包成Jar后,如何指定多个启动类中的其中一个?

在模块化开发或微服务架构中,一个Spring Boot项目可能包含多个带有@SpringBootApplication注解的启动类。将项目打包成单个Jar文件后,如何指定哪个类作为程序入口点就显得至关重要。本文将详细介绍解决方法。

问题根源在于,Spring Boot打包工具在遇到多个启动类时,无法自动确定哪个类应该作为程序入口。Maven或Gradle可能会产生冲突,或者只选择其中一个,这缺乏灵活性。

解决方案:利用Spring Boot Maven插件的mainClass属性。

通过在pom.xml文件中配置mainClass属性,可以明确指定Jar包的入口类。 在标签下的标签中找到spring-boot-maven-plugin插件,并在标签内添加mainClass属性,其值为目标启动类的全限定名。

例如,如果你的启动类是com.example.demo.ApplicationOne,则pom.xml配置如下:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <mainClass>com.example.demo.ApplicationOne</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

执行mvn clean package后生成的Jar包,将以com.example.demo.ApplicationOne类作为入口启动。 要启动其他启动类,只需修改mainClass属性的值即可。 请确保mainClass指定的类包含@SpringBootApplication注解。 此方法有效管理和启动包含多个启动类的Spring Boot项目。