如何在Maven中定义条件属性?

问题描述 投票:0回答:3

例如,如果有环境变量

Configuration
,我希望将属性
${env:AAA}
设置为
AAA
;如果没有这样的环境变量,则设置为其他一些常量值。

如何在 Maven 2 中做到这一点?

maven maven-2
3个回答
12
投票

看起来好像您有条件地激活配置文件...

<profiles>
  <profile>
    <activation>
      <property>
        <name>environment</name>
        <value>test</value>
      </property>
    </activation>
    ...
  </profile>
</profiles>

当环境变量定义为值

test
时,配置文件将被激活,如以下命令所示:

mvn ... -Denvironment=test


11
投票

如果系统属性是可接受的,您可以简单地在 POM 文件中定义该属性并在需要时覆盖:

<project>
...
  <properties>
     <foo.bar>hello</foo.bar>
  </properties>
...
</project>

您可以通过参考

${foo.bar}
在 POM 中的其他位置引用此属性。要在命令行上覆盖,只需传递一个新值:

mvn -Dfoo.bar=goodbye ...

10
投票

您可以使用 maven-antrun-plugin 有条件地设置属性。设置示例

install.path
+ 回显值:

<plugin>
    <!-- Workaround maven not being able to set a property conditionally based on environment variable -->
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.8</version>
    <executions>
        <execution>
            <phase>validate</phase>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <exportAntProperties>true</exportAntProperties>
                <target>
                    <property environment="env"/>
                    <condition property="install.path" value="${env.INSTALL_HOME}" else="C:\default-install-home">
                        <isset property="env.INSTALL_HOME" />
                    </condition>
                    <echo message="${install.path}"/>
                </target>
            </configuration>
        </execution>
    </executions>
</plugin>
© www.soinside.com 2019 - 2024. All rights reserved.