将 Spring Boot 项目打包成可以独立运行的 jar 包

环境
Windows 11 Pro 23H2 OS build 22631.3447
OpenJDK 64-Bit Server VM Temurin-21.0.2+13 (build 21.0.2+13-LTS, mixed mode, sharing)
Spring Boot, Java version 等版本详见正文内容

1. pom.xml 文件配置

1
2
3
4
5
6
7
8
9
10
<parent>  
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.10</version>
<relativePath/>
</parent>
<properties>
<spring-boot.version>3.1.10</spring-boot.version>
<java.version>17</java.version>
</properties>

2. 在 pom.xml 文件添加插件

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
<!-- https://docs.spring.io/spring-boot/docs/3.1.11/maven-plugin/reference/htmlsingle/#packaging -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!-- 若项目未使用 Lombok,则可跳过此配置 -->
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
<!-- 若项目已使用 spring-boot-starter-parent,则无需 repackage 执行 -->
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

3. 打包

运行如下命令,将在 .\target\ 目录内生成 xxx.jar

1
mvn package spring-boot:repackage -Dspring.profiles.active=local

-Dspring.profiles.active=local 用于指定打包环境的配置文件

4. 运行 jar 包

使用以下命令,可以运行 jar

1
java -Dspring.profiles.active=local -jar xxx.jar

-Dspring.profiles.active=local 用于指定运行环境的配置文件

5. 参考

  1. java - SpringBoot no main manifest attribute (maven) - Stack Overflow: https://stackoverflow.com/questions/54867295/springboot-no-main-manifest-attribute-maven
  2. Fixing the No Main Manifest Attribute in Spring Boot | Baeldung: https://www.baeldung.com/spring-boot-fix-the-no-main-manifest-attribute
  3. Spring Boot Maven Plugin Documentation: https://docs.spring.io/spring-boot/docs/3.1.11/maven-plugin/reference/htmlsingle/


将 Spring Boot 项目打包成可以独立运行的 jar 包
https://blog.cc01cc.cn/2024/04/23/package-spring-boot-jar/
作者
零一/cc01cc(zeo)
发布于
2024年4月23日
许可协议