问题展现
现在使用springboot开发spring项目是真的方便快捷,程序开发完成之后,直接打包成一个可执行jar文件,就可以在java环境中运行。那对于新手小伙伴来说,可能会碰到打包好的可执行jar文件无法通过java -jar命令进行启动,报错提示该可执行jar文件中没有主清单属性,如下所示。
![在这里插入图片描述](https://img-blog.csdnimg.cn/ec04ace4b79d4e9e8e6bbe775f6729d4.png)
仔细观察该可执行jar文件,发现其只有KB级大小,显然是有问题的。
![在这里插入图片描述](https://img-blog.csdnimg.cn/6232d6ed76b3473682e30148307e4eef.png)
问题解决
在springboot项目的pom.xml文件中,添加以下节点内容,并重新打包。
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.2.1.RELEASE</version>
</plugin>
</plugins>
</build>
![在这里插入图片描述](https://img-blog.csdnimg.cn/4d3b1e39ec1c40539604a458a99da3a8.png)
可以看到,加上这段内容之后,重新打包后的jar文件大小就是MB级,再次使用java -jar命令启动也再没有问题。
原理说明
在oracle官网的java文档中有一段话作者进行了部分截取。
The java command starts a Java application.
If the -jar option is specified, its argument is the name of the JAR file containing class and resource files for the application.
The startup class must be indicated by the Main-Class manifest header in its source code.
翻译过来就是说,java命令是用来启动一个java应用的,如果java命令后接了-jar选项,那么紧跟的参数就是可执行jar文件的名字,这个可执行jar文件包含了编译好的字节码文件以及资源文件。启动类必须通过源码中的manifest头的Main-Class属性指定。
简单点说,java -jar 命令执行的时候,会去运行可执行jar文件的META-INF/MANIFEST.MF文件中的Main-Class属性指定的类,如果没有找到,就会报没有主清单的错误。
加了spring-boot-maven-plugin插件生成的MANIFEST.MF文件
![在这里插入图片描述](https://img-blog.csdnimg.cn/0d23d3f9876f490da98126d58e58352e.png)
没加spring-boot-maven-plugin插件生成的MANIFEST.MF文件
![在这里插入图片描述](https://img-blog.csdnimg.cn/213627ed91294d53ab9b658146be68cc.png)