项目在IDEA中使用Maven编译打包后,运行该jar包报错提示如下:
$ java -jar data-collect-gateway-1.0-SNAPSHOT.jar
data-collect-gateway-1.0-SNAPSHOT.jar中没有主清单属性
使用jar命令解开jar包 或者使用压缩工具打开jar找,找到META-INF文件夹下的MANIFEST.MF文件,我们看一下这个清单文件内容。(补充jar命令解开jar包:jar -xvf xxxx.jar )
$ cat MANIFEST.MF
Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Built-By: machenjun
Created-By: Apache Maven 3.8.1
Build-Jdk: 1.8.0_252
我们发现这里没有Main-Class等信息,大多数的问题产生的原因是在项目pom文件中没有配置spring-boot-maven-plugin插件。一般的解决办法,就是配置该maven插件。
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
</plugin>
</plugins>
</build>
这种解决方案通常可以解决大部分问题,但这种方案只在使用 spring-boot-starter-parent 为 标签内容时才有效,当我们使用自定义的节点时按如上所述的方式配置maven插件则是无效的,这是为什么呢?让我们一起看一看 spring-boot-starter-parent 中的配置。
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>${start-class}</mainClass>
</configuration>
</plugin>
我们可以看到这里配置了主类信息以及一个重要的标签<goals>
,对repackage的描述如下:
<goal>repackage</goal>
<description>Repackage existing JAR and WAR archives so that they can be executed from the command
line using {@literal java -jar}. With <code>layout=NONE</code> can also be used simply
to package a JAR with nested dependencies (and no main class, so not executable).</description>
看到这里我们就清楚了,当使用自定义的 parent 时,我们需要自行配置maven插件的<goals>
属性,如下:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.xx.xx.gateway.GatewayApplication</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
配置完成,重新编译打包测试,再来看一下清单文件MANIFEST.MF:
$ cat MANIFEST.MF
Manifest-Version: 1.0
Spring-Boot-Classpath-Index: BOOT-INF/classpath.idx
Archiver-Version: Plexus Archiver
Built-By: machenjun
Start-Class: com.xx.xx.gateway.GatewayApplication
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Spring-Boot-Version: 2.3.7.RELEASE
Created-By: Apache Maven 3.8.1
Build-Jdk: 1.8.0_252
Main-Class: org.springframework.boot.loader.JarLauncher
清单文件信息齐全,再使用java -jar 命名启动jar包,就可以正常启动了。