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

pom.xml environment variable with default fallback

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

${env.BUILD_NUMBER:0}

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

<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>

比bash...

更冗长一点

我对公认的方法不是很满意,所以我对其进行了一些简化。

基本上在普通属性块中设置一个默认值 属性,并且只在适当的时候覆盖(而不是有效的 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>