详解SpringBoot迭代发布JAR瘦身配置

时间:2022-09-06 10:53:22

默认情况下,插件 spring-boot-maven-plugin 会把整个项目打包成一个可运行的jar包(即所谓的flat jar),导致了这个jar包很大(通常有几十m+)。如今迭代发布时常有的事情,每次都上传一个如此庞大的文件,会浪费很多时间,有些时候上传的过程中还会出错。

造成jar包很大的根本原因就是依赖第三方的jar很多,很大,下面我们就把第三方的jar与项目代码分离,第三方的jar把移除到lib文件夹中,即可实现为我们的可执行jar瘦身,配置如下:

?
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
<plugins>
  <!-- spring boot thin jar configuration -->
  <plugin>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-maven-plugin</artifactid>
    <configuration>
      <!-- main 入口 -->
      <mainclass>com.bdfint.logistics.app.driver.logisticsappdriverapplication</mainclass>
      <!-- 设置为zip,此模式下spring-boot-maven-plugin会将manifest.mf文件中的main-class设置为org.springframework.boot.loader.propertieslauncher -->
      <layout>zip</layout>
      <!-- 需要包含的jar包 -->
      <includes>
        <!-- 不包含任何jar包 -->
        <!--<include>-->
          <!--<groupid>nothing</groupid>-->
          <!--<artifactid>nothing</artifactid>-->
        <!--</include>-->
        <include>
          <groupid>com.bdfint.logistics</groupid>
          <artifactid>logistics-api</artifactid>
        </include>
        <include>
          <groupid>com.bdfint.logistics</groupid>
          <artifactid>logistics-common</artifactid>
        </include>
      </includes>
    </configuration>
    <executions>
      <execution>
        <goals>
          <goal>repackage</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
  <!-- third-party jar into lib directory -->
  <plugin>
    <groupid>org.apache.maven.plugins</groupid>
    <artifactid>maven-dependency-plugin</artifactid>
    <executions>
      <execution>
        <id>copy-dependencies</id>
        <phase>prepare-package</phase>
        <goals>
          <goal>copy-dependencies</goal>
        </goals>
        <configuration>
          <outputdirectory>${project.build.directory}/lib</outputdirectory>
          <!-- 需要排除的jar的 groupid -->
          <excludegroupids>
            com.bdfint.logistics
          </excludegroupids>
        </configuration>
      </execution>
    </executions>
  </plugin>
</plugins>

接下来,执行打包命令:mvn clean package -dmaven.test.skip=true,打包后在target目录下就包含我们的jar和lib目录,如下图:

详解SpringBoot迭代发布JAR瘦身配置

cmd定位到target目录下,执行命令:java -dloader.path=./lib -jar logistics-app-driver-2.9.1.1.jar,即可把项目jar跑起来!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://my.oschina.net/u/2919251/blog/1927003