具有默认回退的pom.xml环境变量

Gav*_*iel 12 environment-variables pom.xml maven

我希望能够使用环境变量(如果已设置)或我在pom.xml中设置的默认回退值,类似于bash中的$ {VARIABLE:-default}.可能吗?就像是:

${env.BUILD_NUMBER:0}
Run Code Online (Sandbox Code Playgroud)

ner*_*ler 24

我对接受的方法并不满意,所以我对它进行了简化.

基本上在普通属性块中设置默认属性,并且只在适当时覆盖(而不是有效的switch语句):

<properties>
     <!-- Sane default -->
    <buildNumber>0</buildNumber>
    <!-- the other props you use -->
</properties>

<profiles>
    <profile>
        <id>ci</id>
        <activation>
            <property>
                <name>env.buildNumber</name>
            </property>
        </activation>
        <properties>
            <!-- Override only if necessary -->
            <buildNumber>${env.buildNumber}</buildNumber>
        </properties>
    </profile>
</profiles>
Run Code Online (Sandbox Code Playgroud)


Ste*_*neM 10

您可以使用配置文件来实现此目的:

<profiles> 
    <profile>
        <id>buildnumber-defined</id>
        <activation>
            <property>
                <name>env.BUILD_NUMBER</name>
            </property>
        </activation>
        <properties>
            <buildnumber>${env.BUILD_NUMBER}</buildnumber>
        </properties>
    </profile>
    <profile>
        <id>buildnumber-undefined</id>
        <activation>
            <property>
                <name>!env.BUILD_NUMBER</name>
            </property>
        </activation>
        <properties>
            <buildnumber>0</buildnumber>
        </properties>
    </profile>
</profiles>
Run Code Online (Sandbox Code Playgroud)

比bash更冗长......

  • 据我所知,您不需要为此提供两个配置文件(至少在最近的 maven 版本中)。您可以在顶级 `&lt;properties&gt;` 中提供默认值,然后它只会被自定义激活(本答案中的第一个配置文件)覆盖。节省 11 行 :) (2认同)