1、优化目的
springboot项目默认打包方式为fat jar,即把所有的依赖打进一个jar包,导致的结果是jar包非常大,远程部署需要花费大量时间传输jar包,影响测试效率和整体项目进度。许多基础的jar包每个项目都需要依赖,造成不必要的资源浪费。
2、如何优化
1.下载插件包,如果maven仓库有则不需要下载,下载完成后可以去掉该依赖
<dependency>
<!-- 加入该配置,使用maven package,依赖jar不会打包在项目最终jar文件内 -->
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-thin-layout</artifactId>
<version>1.0.25.RELEASE</version>
</dependency>
2.加入依赖插件,第二个插件主要为测试项目启动使用,会下载项目依赖的jar包至
项目/target/thin/root/repository
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<dependency>
<!-- 加入该配置,使用maven package,依赖jar不会打包在项目最终jar文件内 -->
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-thin-layout</artifactId>
<version>1.0.25.RELEASE</version>
</dependency>
</dependencies>
</plugin>
<!-- 加入该配置,maven package执行时会在target目录整理好依赖包 -->
<plugin>
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-thin-maven-plugin</artifactId>
<version>1.0.25.RELEASE</version>
<executions>
<execution>
<!-- Download the dependencies at build time -->
<id>resolve</id>
<goals>
<goal>resolve</goal>
</goals>
<inherited>false</inherited>
</execution>
</executions>
</plugin>
3.打包
cd 项目
mvn clean package
4.命令行方式启动项目测试。如service.app.aggregate项目
cd 项目/target/thin/root
java -Dthin.root=. -jar service.app.aggregate-v1.0.jar
5.测试接口功能是否正常
6.所有测试通过后pom.xml仅增加如下插件提交至代码库
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<dependency>
<!-- 加入该配置,使用maven package,依赖jar不会打包在项目最终jar文件内 -->
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-thin-layout</artifactId>
<version>1.0.25.RELEASE</version>
</dependency>
</dependencies>
</plugin>
3、常见问题
-
启动报错。
ide工具是否能正常启动项目?查看启动或报错日志,对比pom中依赖和repository中依赖是否一致?检查maven远程仓库地址是否为国内可用私服?repository中所有的依赖是否全部下载,从没下载的jar包对应的项目中继续排查问题。
4、参考资料
https://github.com/spring-projects-experimental/spring-boot-thin-launcher
https://www.baeldung.com/spring-boot-thin-jar