在开发中,用到springboot项目,当打包后部署运行时,出现了这个问题,网上搜了好多,又是加META-INF配置,又是加啥的,感觉springboot这么方便,这种问题怎么可能会搞这么复杂,于是研究了一下:
首先我们项目要依赖springboot的parent或者引入spring-boot-dependencies
或者
这样就将springboot的pom文件导入了我们的项目,然后还要再要运行的jar包中写入插件:
当使用继承spring-boot-starter-parent时,就会出现标志,表示是继承自父类的,然后我们点到spring-boot-starter-parent的pom文件中,查看插件部分:
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> </execution> </executions> <configuration> <mainClass>${start-class}</mainClass> </configuration> </plugin> <plugin> <artifactId>maven-shade-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"> <resource>META-INF/spring.handlers</resource> </transformer> <transformer implementation="org.springframework.boot.maven.PropertiesMergingResourceTransformer"> <resource>META-INF/spring.factories</resource> </transformer> <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"> <resource>META-INF/spring.schemas</resource> </transformer> <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>${start-class}</mainClass> </transformer> </transformers> </configuration> </execution> </executions> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.1.12.RELEASE</version> </dependency> </dependencies> <configuration> <keepDependenciesWithProvidedScope>true</keepDependenciesWithProvidedScope> <createDependencyReducedPom>true</createDependencyReducedPom> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> </configuration> </plugin>
注意到里面有一个${start-class}变量,这个变量在parent的pom文件中并没有定义,那么我们就在自己要打jar包运行的模块定义这个变量:
然后再打包,就可以直接通过java -jar *.jar 运行项目了
如果不是继承自parnetxml,而是选择第一种,导入dependencies的方式:
那么就要改一下前面的spring-boot-maven-plugin插件,
我们需要指定打包路径的main方法,这样就可以直接打包通过 java -jar *.jar的方式运行了
重要的是一定要定义start-class变量