Java:优化SpringBoot 打包后的jar包体积

通过打包优化,可以将SpringBoot 打包后的jar包体积大大的减小,加快传输效率,减少部署时间

将SpringBoot 打包后的jar包解压可以得到3个文件夹

$ tree -d
.
├── BOOT-INF
│   ├── classes      # 自己编写的代码
│   └── lib          # 第三方依赖jar
├── META-INF
└── org

正常打包

默认的配置 pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

启动方式

# 打包
$ maven package

# 启动项目
$ java -jar ./target/demo-0.0.1-SNAPSHOT.jar

优化打包

将正常打包后的产物,这里是./target/demo-0.0.1-SNAPSHOT.jar,解压

# 拷贝lib文件夹到target目录
cp -R ./target/demo-0.0.1-SNAPSHOT/BOOT-INF/lib ./target

优化的配置 pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>

            <configuration>
                <!--指定项目的启动类-->
                <mainClass>com.example.demo.Application</mainClass>
                <layout>ZIP</layout>

                <!-- 导入依赖 jar -->
                <includes>
                    <include>
                        <groupId>nothing</groupId>
                        <artifactId>nothing</artifactId>
                    </include>
                </includes>
            </configuration>

            <executions>
                <execution>
                    <goals>
                        <!--剔除其它的依赖,只需要保留最简单的结构-->
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

启动方式

# 打包
$ maven package

# 启动项目
java -Dloader.path=./target/lib -jar ./target/demo-0.0.2-SNAPSHOT.jar

对比优化前后的jar包体积大小,明显可以看到优化后的效果

$ ls -lh target/

25M  demo-0.0.1-SNAPSHOT.jar
156K demo-0.0.2-SNAPSHOT.jar

参考文章

猜你喜欢

转载自blog.csdn.net/mouday/article/details/131056327