Spring Boot 程序我们一般会设置使用 spring-boot-maven-plugin
来生成 jar 包,配置类似于:
<properties>
<start-class>com.example.AppMain</start-class>
<final-name>example</final-name>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<finalName>${final-name}</finalName>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
这样我们可以通过 -jar
的方式直接启动并执行指定的 start-class
类的 main 函数:
$ java [options] -jar example.jar [args..]
但当我们需要指定并执行其他类的 main 函数时,使用 -cp
参数却行不通:
$ java [options] -cp example.jar com.example.AlternativeClass [args..]
错误: 找不到或无法加载主类
因为 Spring Boot 打包时做了处理,启动时的主类也不再是用户指定的,而是由 Spring Boot 启动后代为调用执行。
此时我们就需要一些 trick 来解决这个问题。
首先我们要改变 spring-boot-maven-plugin
的参数:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<finalName>${final-name}</finalName>
<layout>ZIP</layout>
</configuration>
</execution>
</executions>
</plugin>
增加了 <layout>ZIP</layout>
一行。这将使 Spring Boot 使用 PropertiesLauncher
。
然后
$ java [options] -cp example.jar -Dloader.main=com.example.AlternativeClass
org.springframework.boot.loader.PropertiesLauncher [args..]
可以看到,事实上是以 org.springframework.boot.loader.PropertiesLauncher
作为主类启动的,设置了 loader.main
的值,由 Spring Boot 调用执行。
参考文章:
网友评论