Skip to content

Maven 生命周期与插件

TIP

Maven 的生命周期定义了构建过程中的阶段顺序,插件则在特定阶段执行任务。

三大生命周期

Clean 生命周期

pre-clean → clean → post-clean

Default 生命周期(核心)

validate → compile → test → package → verify → install → deploy

Site 生命周期

pre-site → site → post-site → site-deploy

阶段绑定

各阶段默认绑定的插件目标:

阶段插件目标
compilemaven-compiler-plugincompile
testmaven-surefire-plugintest
packagemaven-jar-pluginjar
installmaven-install-plugininstall
deploymaven-deploy-plugindeploy

常用插件配置

xml
<build>
    <plugins>
        <!-- 编译器配置 -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.10.1</version>
            <configuration>
                <source>11</source>
                <target>11</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>

        <!-- 打可执行 JAR 包 -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.3.0</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals><goal>shade</goal></goals>
                    <configuration>
                        <transformers>
                            <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>com.example.App</mainClass>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

自定义插件执行

bash
# 跳过测试
mvn package -DskipTests

# 使用指定 Profile
mvn clean package -Pprod

# 指定阶段执行到某个步骤
mvn compile           # 只编译
mvn test              # 执行到测试阶段
mvn clean install     # 清理并安装到本地仓库

TIP

理解 Maven 生命周期有助于排查构建问题。例如测试失败可以通过跳过测试来快速验证编译和打包是否正确。