maven-build-lifecycle

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Maven Build Lifecycle

Maven 构建生命周期

Master Maven's build lifecycle including phases, goals, profiles, and build customization for efficient Java project builds.
掌握Maven的构建生命周期,包括阶段、目标、配置文件和构建自定义,以实现高效的Java项目构建。

Overview

概述

Maven's build lifecycle is a well-defined sequence of phases that execute in order. Understanding the lifecycle is essential for effective build configuration and optimization.
Maven的构建生命周期是一套定义明确的阶段序列,按顺序执行。理解生命周期对于有效的构建配置和优化至关重要。

Default Lifecycle Phases

默认生命周期阶段

Complete Phase Order

完整阶段顺序

1.  validate      - Validate project structure
2.  initialize    - Initialize build state
3.  generate-sources
4.  process-sources
5.  generate-resources
6.  process-resources - Copy resources to output
7.  compile       - Compile source code
8.  process-classes
9.  generate-test-sources
10. process-test-sources
11. generate-test-resources
12. process-test-resources
13. test-compile  - Compile test sources
14. process-test-classes
15. test          - Run unit tests
16. prepare-package
17. package       - Create JAR/WAR
18. pre-integration-test
19. integration-test - Run integration tests
20. post-integration-test
21. verify        - Run verification checks
22. install       - Install to local repo
23. deploy        - Deploy to remote repo
1.  validate      - 验证项目结构
2.  initialize    - 初始化构建状态
3.  generate-sources
4.  process-sources
5.  generate-resources
6.  process-resources - 将资源复制到输出目录
7.  compile       - 编译源代码
8.  process-classes
9.  generate-test-sources
10. process-test-sources
11. generate-test-resources
12. process-test-resources
13. test-compile  - 编译测试代码
14. process-test-classes
15. test          - 运行单元测试
16. prepare-package
17. package       - 创建JAR/WAR包
18. pre-integration-test
19. integration-test - 运行集成测试
20. post-integration-test
21. verify        - 运行验证检查
22. install       - 安装到本地仓库
23. deploy        - 部署到远程仓库

Common Phase Commands

常用阶段命令

bash
undefined
bash
undefined

Compile only

仅编译

mvn compile
mvn compile

Compile and run tests

编译并运行测试

mvn test
mvn test

Create package

创建包

mvn package
mvn package

Install to local repository

安装到本地仓库

mvn install
mvn install

Deploy to remote repository

部署到远程仓库

mvn deploy
mvn deploy

Clean and build

清理并构建

mvn clean install
mvn clean install

Skip tests

跳过测试

mvn install -DskipTests
mvn install -DskipTests

Skip test compilation and execution

跳过测试编译与执行

mvn install -Dmaven.test.skip=true
undefined
mvn install -Dmaven.test.skip=true
undefined

Clean Lifecycle

清理生命周期

1. pre-clean
2. clean         - Delete target directory
3. post-clean
bash
undefined
1. pre-clean
2. clean         - 删除target目录
3. post-clean
bash
undefined

Clean build artifacts

清理构建产物

mvn clean
mvn clean

Clean specific directory

清理指定目录

mvn clean -DbuildDirectory=out
undefined
mvn clean -DbuildDirectory=out
undefined

Site Lifecycle

站点生命周期

1. pre-site
2. site          - Generate documentation
3. post-site
4. site-deploy   - Deploy documentation
bash
undefined
1. pre-site
2. site          - 生成文档
3. post-site
4. site-deploy   - 部署文档
bash
undefined

Generate site

生成站点

mvn site
mvn site

Generate and deploy site

生成并部署站点

mvn site-deploy
undefined
mvn site-deploy
undefined

Goals vs Phases

目标 vs 阶段

Executing Phases

执行阶段

bash
undefined
bash
undefined

Execute phase (runs all previous phases)

执行阶段(会运行所有前置阶段)

mvn package
undefined
mvn package
undefined

Executing Goals

执行目标

bash
undefined
bash
undefined

Execute specific goal

执行特定目标

mvn compiler:compile mvn surefire:test mvn jar:jar
mvn compiler:compile mvn surefire:test mvn jar:jar

Multiple goals

多个目标

mvn dependency:tree compiler:compile
undefined
mvn dependency:tree compiler:compile
undefined

Phase-to-Goal Bindings

阶段与目标的绑定

xml
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.12.1</version>
            <executions>
                <execution>
                    <id>compile-sources</id>
                    <phase>compile</phase>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
xml
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.12.1</version>
            <executions>
                <execution>
                    <id>compile-sources</id>
                    <phase>compile</phase>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Build Profiles

构建配置文件

Profile Definition

配置文件定义

xml
<profiles>
    <profile>
        <id>development</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <env>dev</env>
            <skip.integration.tests>true</skip.integration.tests>
        </properties>
    </profile>

    <profile>
        <id>production</id>
        <properties>
            <env>prod</env>
            <skip.integration.tests>false</skip.integration.tests>
        </properties>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <debug>false</debug>
                        <optimize>true</optimize>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
xml
<profiles>
    <profile>
        <id>development</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <env>dev</env>
            <skip.integration.tests>true</skip.integration.tests>
        </properties>
    </profile>

    <profile>
        <id>production</id>
        <properties>
            <env>prod</env>
            <skip.integration.tests>false</skip.integration.tests>
        </properties>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <debug>false</debug>
                        <optimize>true</optimize>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

Profile Activation

配置文件激活

bash
undefined
bash
undefined

Activate by name

通过名称激活

mvn install -Pproduction
mvn install -Pproduction

Multiple profiles

多个配置文件

mvn install -Pproduction,ci
mvn install -Pproduction,ci

Deactivate profile

禁用配置文件

mvn install -P!development
undefined
mvn install -P!development
undefined

Activation Triggers

激活触发器

xml
<profile>
    <id>jdk17</id>
    <activation>
        <!-- Activate by JDK version -->
        <jdk>17</jdk>
    </activation>
</profile>

<profile>
    <id>windows</id>
    <activation>
        <!-- Activate by OS -->
        <os>
            <family>windows</family>
        </os>
    </activation>
</profile>

<profile>
    <id>ci</id>
    <activation>
        <!-- Activate by environment variable -->
        <property>
            <name>env.CI</name>
            <value>true</value>
        </property>
    </activation>
</profile>

<profile>
    <id>with-config</id>
    <activation>
        <!-- Activate by file existence -->
        <file>
            <exists>src/main/config/app.properties</exists>
        </file>
    </activation>
</profile>
xml
<profile>
    <id>jdk17</id>
    <activation>
        <!-- 按JDK版本激活 -->
        <jdk>17</jdk>
    </activation>
</profile>

<profile>
    <id>windows</id>
    <activation>
        <!-- 按操作系统激活 -->
        <os>
            <family>windows</family>
        </os>
    </activation>
</profile>

<profile>
    <id>ci</id>
    <activation>
        <!-- 按环境变量激活 -->
        <property>
            <name>env.CI</name>
            <value>true</value>
        </property>
    </activation>
</profile>

<profile>
    <id>with-config</id>
    <activation>
        <!-- 按文件存在性激活 -->
        <file>
            <exists>src/main/config/app.properties</exists>
        </file>
    </activation>
</profile>

Resource Filtering

资源过滤

Enable Filtering

启用过滤

xml
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>false</filtering>
            <excludes>
                <exclude>**/*.properties</exclude>
                <exclude>**/*.xml</exclude>
            </excludes>
        </resource>
    </resources>
</build>
xml
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>false</filtering>
            <excludes>
                <exclude>**/*.properties</exclude>
                <exclude>**/*.xml</exclude>
            </excludes>
        </resource>
    </resources>
</build>

Property Substitution

属性替换

properties
undefined
properties
undefined

application.properties

application.properties

app.name=${project.name} app.version=${project.version} app.environment=${env} build.timestamp=${maven.build.timestamp}
undefined
app.name=${project.name} app.version=${project.version} app.environment=${env} build.timestamp=${maven.build.timestamp}
undefined

Build Customization

构建自定义

Source and Target Configuration

源码与目标版本配置

xml
<properties>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
    <maven.compiler.release>17</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
xml
<properties>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
    <maven.compiler.release>17</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

Custom Source Directories

自定义源码目录

xml
<build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
        </testResource>
    </testResources>
</build>
xml
<build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
        </testResource>
    </testResources>
</build>

Final Name and Output

最终名称与输出

xml
<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
    <directory>target</directory>
    <outputDirectory>target/classes</outputDirectory>
    <testOutputDirectory>target/test-classes</testOutputDirectory>
</build>
xml
<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
    <directory>target</directory>
    <outputDirectory>target/classes</outputDirectory>
    <testOutputDirectory>target/test-classes</testOutputDirectory>
</build>

Multi-Module Builds

多模块构建

Reactor Options

反应堆选项

bash
undefined
bash
undefined

Build all modules

构建所有模块

mvn install
mvn install

Build specific module and dependencies

构建指定模块及其依赖

mvn install -pl module-name -am
mvn install -pl module-name -am

Build dependents of a module

构建指定模块的依赖模块

mvn install -pl module-name -amd
mvn install -pl module-name -amd

Resume from specific module

从指定模块恢复构建

mvn install -rf :module-name
mvn install -rf :module-name

Build in parallel

并行构建

mvn install -T 4 mvn install -T 1C # 1 thread per CPU core
undefined
mvn install -T 4 mvn install -T 1C # 每个CPU核心分配1个线程
undefined

Module Order Control

模块顺序控制

xml
<!-- parent/pom.xml -->
<modules>
    <module>common</module>
    <module>api</module>
    <module>service</module>
    <module>web</module>
</modules>
xml
<!-- parent/pom.xml -->
<modules>
    <module>common</module>
    <module>api</module>
    <module>service</module>
    <module>web</module>
</modules>

Test Configuration

测试配置

Surefire Plugin (Unit Tests)

Surefire 插件(单元测试)

xml
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.2.3</version>
    <configuration>
        <includes>
            <include>**/*Test.java</include>
            <include>**/*Tests.java</include>
        </includes>
        <excludes>
            <exclude>**/*IntegrationTest.java</exclude>
        </excludes>
        <parallel>methods</parallel>
        <threadCount>4</threadCount>
        <forkCount>1</forkCount>
        <reuseForks>true</reuseForks>
    </configuration>
</plugin>
xml
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.2.3</version>
    <configuration>
        <includes>
            <include>**/*Test.java</include>
            <include>**/*Tests.java</include>
        </includes>
        <excludes>
            <exclude>**/*IntegrationTest.java</exclude>
        </excludes>
        <parallel>methods</parallel>
        <threadCount>4</threadCount>
        <forkCount>1</forkCount>
        <reuseForks>true</reuseForks>
    </configuration>
</plugin>

Failsafe Plugin (Integration Tests)

Failsafe 插件(集成测试)

xml
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>3.2.3</version>
    <executions>
        <execution>
            <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <includes>
            <include>**/*IT.java</include>
            <include>**/*IntegrationTest.java</include>
        </includes>
    </configuration>
</plugin>
xml
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>3.2.3</version>
    <executions>
        <execution>
            <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <includes>
            <include>**/*IT.java</include>
            <include>**/*IntegrationTest.java</include>
        </includes>
    </configuration>
</plugin>

Build Optimization

构建优化

Incremental Builds

增量构建

bash
undefined
bash
undefined

Skip unchanged modules

跳过未修改的模块

mvn install -amd
mvn install -amd

Use build cache (requires Maven Daemon)

使用构建缓存(需要Maven Daemon)

mvnd install
undefined
mvnd install
undefined

Parallel Builds

并行构建

xml
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <fork>true</fork>
                <compilerArgs>
                    <arg>-J-Xmx512m</arg>
                </compilerArgs>
            </configuration>
        </plugin>
    </plugins>
</build>
xml
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <fork>true</fork>
                <compilerArgs>
                    <arg>-J-Xmx512m</arg>
                </compilerArgs>
            </configuration>
        </plugin>
    </plugins>
</build>

Build Cache

构建缓存

bash
undefined
bash
undefined

Enable build cache (Maven 4+)

启用构建缓存(Maven 4+)

mvn install -Dmaven.build.cache.enabled=true
undefined
mvn install -Dmaven.build.cache.enabled=true
undefined

Debugging Builds

构建调试

Verbose Output

详细输出

bash
undefined
bash
undefined

Debug mode

调试模式

mvn install -X
mvn install -X

Error stacktrace

错误堆栈跟踪

mvn install -e
mvn install -e

Quiet mode

静默模式

mvn install -q
undefined
mvn install -q
undefined

Effective POM

有效POM

bash
undefined
bash
undefined

View resolved POM

查看解析后的POM

mvn help:effective-pom
mvn help:effective-pom

View effective settings

查看有效设置

mvn help:effective-settings
mvn help:effective-settings

Active profiles

查看激活的配置文件

mvn help:active-profiles
undefined
mvn help:active-profiles
undefined

Dependency Analysis

依赖分析

bash
undefined
bash
undefined

Check plugin versions

检查插件版本更新

mvn versions:display-plugin-updates
mvn versions:display-plugin-updates

Check dependency versions

检查依赖版本升级

mvn versions:display-dependency-updates
undefined
mvn versions:display-dependency-updates
undefined

Best Practices

最佳实践

  1. Use Clean Builds - Run
    mvn clean
    before releases
  2. Consistent Versions - Lock plugin versions
  3. Profile Isolation - Keep profiles focused
  4. Fail Fast - Use
    -ff
    in CI for quick feedback
  5. Parallel Builds - Use
    -T
    for multi-module projects
  6. Skip Wisely - Know the difference between skip options
  7. Resource Filtering - Enable only where needed
  8. Test Separation - Unit tests in Surefire, integration in Failsafe
  9. Reproducible Builds - Pin all plugin versions
  10. Document Profiles - Comment profile purposes
  1. 使用清理构建 - 在发布前运行
    mvn clean
  2. 版本一致性 - 锁定插件版本
  3. 配置文件隔离 - 保持配置文件聚焦单一用途
  4. 快速失败 - 在CI环境中使用
    -ff
    获取快速反馈
  5. 并行构建 - 对多模块项目使用
    -T
    参数
  6. 合理跳过 - 了解不同跳过选项的差异
  7. 资源过滤 - 仅在需要时启用
  8. 测试分离 - 单元测试用Surefire,集成测试用Failsafe
  9. 可复现构建 - 固定所有插件版本
  10. 文档化配置文件 - 为配置文件添加注释说明用途

Common Pitfalls

常见陷阱

  1. Skipping Tests - Don't skip tests in CI
  2. SNAPSHOT in Release - Remove snapshots before release
  3. Missing Clean - Stale files causing issues
  4. Profile Conflicts - Overlapping profile configurations
  5. Resource Filtering - Accidentally filtering binaries
  6. Phase Confusion - Running wrong phase
  7. Memory Issues - Insufficient heap for large builds
  8. Reactor Order - Module dependency issues
  1. 跳过测试 - 不要在CI环境中跳过测试
  2. 发布中包含SNAPSHOT - 发布前移除SNAPSHOT依赖
  3. 未执行清理 - 陈旧文件导致问题
  4. 配置文件冲突 - 重叠的配置文件配置
  5. 资源过滤 - 意外过滤二进制文件
  6. 阶段混淆 - 运行错误的阶段
  7. 内存问题 - 大型构建堆内存不足
  8. 反应堆顺序 - 模块依赖问题

CI/CD Integration

CI/CD 集成

GitHub Actions

GitHub Actions

yaml
- name: Build with Maven
  run: mvn -B clean verify -Pci

- name: Release
  run: mvn -B deploy -Prelease -DskipTests
yaml
- name: Build with Maven
  run: mvn -B clean verify -Pci

- name: Release
  run: mvn -B deploy -Prelease -DskipTests

Jenkins Pipeline

Jenkins 流水线

groovy
stage('Build') {
    steps {
        sh 'mvn -B clean package -DskipTests'
    }
}
stage('Test') {
    steps {
        sh 'mvn -B test'
    }
}
stage('Integration Test') {
    steps {
        sh 'mvn -B verify -DskipUnitTests'
    }
}
groovy
stage('Build') {
    steps {
        sh 'mvn -B clean package -DskipTests'
    }
}
stage('Test') {
    steps {
        sh 'mvn -B test'
    }
}
stage('Integration Test') {
    steps {
        sh 'mvn -B verify -DskipUnitTests'
    }
}

When to Use This Skill

何时使用此技能

  • Setting up new Maven projects
  • Customizing build phases
  • Creating build profiles for environments
  • Configuring test execution
  • Optimizing build performance
  • Debugging build failures
  • Setting up CI/CD pipelines
  • Multi-module project configuration
  • 搭建新的Maven项目
  • 自定义构建阶段
  • 为不同环境创建构建配置文件
  • 配置测试执行
  • 优化构建性能
  • 调试构建失败
  • 搭建CI/CD流水线
  • 多模块项目配置