You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按打包方式激活Maven Profile?(Maven 3.9.0新特性)

Maven 3.9.0 按打包方式激活Profile的实现示例

Maven 3.9.0新增了通过<packaging>类型激活Profile的功能,以下是几种常见的实现场景:

1. 基础场景:单一打包类型激活Profile

当项目打包为war时激活web-profile,打包为jar时激活core-profile,示例pom.xml片段如下:

<profiles>
    <!-- Web项目专属Profile -->
    <profile>
        <id>web-profile</id>
        <activation>
            <packaging>war</packaging>
        </activation>
        <properties>
            <deploy.target>tomcat</deploy.target>
        </properties>
        <!-- 可添加web项目依赖、插件配置等 -->
    </profile>

    <!-- 核心Jar项目专属Profile -->
    <profile>
        <id>core-profile</id>
        <activation>
            <packaging>jar</packaging>
        </activation>
        <properties>
            <deploy.target>maven-repo</deploy.target>
        </properties>
        <!-- 可添加jar项目专属配置 -->
    </profile>
</profiles>

2. 多打包类型匹配同一Profile

如果需要多个打包类型(比如war和ear)都激活同一个Profile,可以通过多个<value>标签或逗号分隔的字符串实现:

<profile>
    <id>enterprise-profile</id>
    <activation>
        <packaging>
            <value>war</value>
            <value>ear</value>
        </packaging>
    </activation>
    <!-- 企业级项目通用配置 -->
</profile>

<!-- 或者用逗号分隔写法 -->
<profile>
    <id>enterprise-profile</id>
    <activation>
        <packaging>war,ear</packaging>
    </activation>
</profile>

3. 结合其他条件的组合激活

可以将打包类型激活与系统属性、环境变量等条件组合使用,比如当打包为jar且存在debug系统属性时激活调试Profile:

<profile>
    <id>debug-jar-profile</id>
    <activation>
        <packaging>jar</packaging>
        <property>
            <name>debug</name>
            <value>true</value>
        </property>
    </activation>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <debug>true</debug>
                    <debuglevel>lines,vars,source</debuglevel>
                </configuration>
            </plugin>
        </plugins>
    </build>
</profile>

验证Profile是否激活

可以通过以下命令查看当前激活的Profile:

# 直接指定打包类型并查看激活的Profile
mvn help:active-profiles -Dmaven.packaging=war

# 或在pom.xml中指定<packaging>后执行
mvn help:active-profiles

内容的提问来源于stack exchange,提问作者JF Meier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 14:02:14