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

2024-04-23 · 215 字 · 约 1 分钟

环境
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 文件配置

<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 文件添加插件

<!-- 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

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

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

# 4. 运行 jar 包

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

java "-Dspring.profiles.active=dev" -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/
  4. java - “Unknown lifecycle phase. You must specify a valid lifecycle phase or a goal error” occurs when trying to run spring boot app with profile - Stack Overflow: https://stackoverflow.com/questions/70473772/unknown-lifecycle-phase-you-must-specify-a-valid-lifecycle-phase-or-a-goal-err