通常Spring Boot打包成一个独立jar包之后,整个用于部署的jar会变得特别大,可能会是一两百M,甚至更大,但是有时候会有某些原因,要求每次增量部署的包不能太大,这时就需要对部署包进行瘦身,我们需要把第三方的依赖包分离出来,可以使用maven插件spring-boot-maven-plugin和maven-dependency-plugin来满足需求。

maven打包配置:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>2.7.3</version>
    <configuration>
        <!--项目的启动类-->
        <mainClass>com.hiofd.tech.main.MyApplication</mainClass>
        <!--解决windows命令行窗口中文乱码-->
        <jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
        <layout>ZIP</layout>
        <!--配置需要打包进项目的jar-->
        <includes>
            <!--这里是填写需要包含进去的jar,
                必须项目中的某些模块,会经常变动,那么就应该将其写进来
                如果没有则non-exists ,表示不打包依赖
            -->
            <!--<include>
                <groupId>non-exists</groupId>
                <artifactId>non-exists</artifactId>
            </include>-->
            <include>
                <groupId>com.hiofd.tech</groupId>
                <artifactId>my-api</artifactId>
            </include>
            <include>
                <groupId>com.hiofd.tech</groupId>
                <artifactId>my-model</artifactId>
            </include>
            <include>
                <groupId>com.hiofd.tech</groupId>
                <artifactId>my-rest</artifactId>
            </include>
            <include>
                <groupId>com.hiofd.tech</groupId>
                <artifactId>my-service</artifactId>
            </include>
        </includes>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<!--此插件用于将依赖包抽出-->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
        <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.build.directory}/lib</outputDirectory>
                <excludeTransitive>false</excludeTransitive>
                <stripVersion>false</stripVersion>
                <includeScope>runtime</includeScope>
                <excludeGroupIds>com.hiofd.tech</excludeGroupIds>
            </configuration>
        </execution>
    </executions>
</plugin>

打包之后,主jar包变小,另外多出一个lib文件夹,里面都是第三方jar包

启动,新增参数-Dloader.path=lib

1
java -Dserver.port=80 -Dloader.path=/app/lib -jar /app/my-main-1.0.0-SNAPSHOT.jar