Spring Boot 瘦身 Jar

95 阅读1分钟

将源代码和依赖的jar 分离开,提高部署效率,以及减小带宽占用

1. pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <executable>true</executable>
                <layout>ZIP</layout>
                <!--这里是填写需要包含进去的jar,
      必须项目中的某些模块,会经常变动,那么就应该将其坐标写进来
      如果没有则nothing ,表示不打包依赖 -->
                <includes>
                    <include>
                        <groupId>nothing</groupId>
                        <artifactId>nothing</artifactId>
                    </include>
                </includes>
            </configuration>
        </plugin>

        <!--拷贝依赖到jar外面的lib目录-->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <!--指定的依赖路径-->
                        <outputDirectory>
                            ${project.build.directory}/lib
                        </outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

2. 打包

mvn clean package

成功之后,会在 target 目录下创建出 lib 目录,以及瘦身后的jar

image.png

3. 启动

启动命令上加上 loader.path 即可

java -Dloader.path=./lib -jar springboot-demo-0.0.1-SNAPSHOT.jar