【问题标题】:pom.xml environment variable with default fallbackpom.xml 具有默认回退的环境变量
【发布时间】:2016-01-12 14:30:45
【问题描述】:

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

${env.BUILD_NUMBER:0}

【问题讨论】:

标签: maven environment-variables pom.xml


【解决方案1】:

我对接受的方法并不满意,所以我稍微简化了一点。

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

【讨论】:

    【解决方案2】:

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

    <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 详细一点...

    【讨论】:

    • 据我所知,我需要通过mvn -P buildnumber-undefined,不是吗?稍后我将如何在 pom.xml 中使用它?
    • 将根据环境变量BUILD_NUMBER 的存在与否激活相应的配置文件。之后属性 buildnumber 应该在你的 pom 中定义,并且可以使用 ${buildnumber} 访问。
    • 据我所知,您不需要两个配置文件(至少在最近的 Maven 版本中)。您可以在顶级 &lt;properties&gt; 中提供默认值,然后它只会被自定义激活(此答案中的第一个配置文件)覆盖。节省 11 行 :)
    • @nerdwaller 你能举个例子吗?你的方法听起来更好。
    • @eggonlegs - 添加为答案,以便显示格式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多