一、前言
本文介绍了几种通过Maven或者Gradle设置Spring Boot应用程序主类的方法。
一个Spring Boot应用程序的主类指的是一个包括public static void main()
方法的类。
默认情况下,如果没有显式地指定主类类的位置,Spring在编译时会在classpath
中进行搜索,如果没有找到或找到多个主类都会导致Spring Boot启动失败。
与传统的Java程序不同,本文中讨论的主类不能通过META-INF/MANIFEST.MF文件中的Main-Class
属性定义。
因为Spring Boot期望Main-Class
属性的值是:
org.springframework.boot.loader.JarLauncher (或WarLauncher)
这意味着直接通过Java命令行传递主类将不能启动我们的Spring Boot应用程序。
一个MANIFEST.MF示例文件可能是这样的:
Manifest-Version: 1.0
Start-Class: org.baeldung.DemoApplication
Main-Class: org.springframework.boot.loader.JarLauncher
作为替代,我们需要使用Start-Class
属性,JarLauncher将使用这个属性的值去启动应用程序。
让我们看一下如何在Maven或Gradle中控制这个属性。
二、Maven
主类在pom.xml文件中可以使用start-class
元素定义:
<properties>
<!-- The main class to start by executing "java -jar" -->
<start-class>org.baeldung.DemoApplication</start-class>
</properties>
请注意,只有当pom.xml文件的parent
元素中设置的是spring-boot-starter-parent
,这个属性才会生效。
此外,还可以在我们的pom文件中使用插件spring-boot-maven-plugin
的mainClass
配置项:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>org.baeldung.DemoApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
一个使用Maven配置主类位置的示例可以在Github上找到。
三、Gradle
如果我们正在使用Spring Boot的Gradle插件,这里还有几个继承自org.springframework.boot
的配置可以指定我们的主类。
在项目的build.gradle文件中,可以通过springBoot
配置块定义mainClassName
。这样可以让bootRun与bootJar任务能使用到它:
springBoot {
mainClassName = 'org.baeldung.DemoApplication'
}
或者,在bootJar任务中定义mainClassName
:
bootJar {
mainClassName = 'org.baeldung.DemoApplication'
}
亦或者,在bootJar任务中定义manifest文件中的Start-Class
属性:
bootJar {
manifest {
attributes 'Start-Class': 'org.baeldung.DemoApplication'
}
}
注意,在bootJar
配置块中进行的配置只能对它自己产生的JAR文件有效。对于其它在Gradle中的Spring Boot任务无效,比如:bootRun
任务。
另外,如果Gradle的application插件被应用到项目中,mainClassName
可以被定义为一个全局属性:
mainClassName = 'org.baeldung.DemoApplication'
我们可以在Github上找到一个关于上述这些Gradle配置的示例。
四、使用命令行
我们还可以通过命令行传递主类的位置。
Spring Boot的org.springframework.boot.loader.PropertiesLauncher
使用一个来自于命令行的参数:loader.main
,它可以让你定义主类的位置:
java -cp bootApp.jar -Dloader.main=org.baeldung.DemoApplication org.springframework.boot.loader.PropertiesLauncher
五、总结
这里介绍了好几种方式用于指定Spring Boot应用程序的入口点。
最重要的是,我们要了解这些方法本质上是在修改JAR或WAR文件中的MANIFEST.MF文件。