如何识别和设置Maven中缺少的环境属性?

TER*_*ytE 10 environment-variables maven

我有我的构建设置,以便通过命令行传入我的变量:

mvn clean install -DsomeVariable=data
Run Code Online (Sandbox Code Playgroud)

在我的pom我有:

<someTag>${someVariable}</someTag>
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我想确定是否在命令行上没有指定someVariable,然后默认它以便我的脚本可以继续.

这可以在Maven完成吗?

Ale*_*yak 13

您可以在propertiesPOM文件的部分中指定默认属性值:

<properties>
  <someVariable>myVariable</someVariable>
</properties>
Run Code Online (Sandbox Code Playgroud)

如果要确保在命令行上始终提供属性值,则可以使用maven-enforcer-plugin.

这是一个链接,显示如何强制执行系统属性 - > http://maven.apache.org/enforcer/enforcer-rules/requireProperty.html

我将在这里逐字复制XML,以防上述链接变坏.

<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-enforcer-plugin</artifactId>
        <version>1.0.1</version>
        <executions>
          <execution>
            <id>enforce-property</id>
            <goals>
              <goal>enforce</goal>
            </goals>
            <configuration>
              <rules>
                <requireProperty>
                  <property>basedir</property>
                  <message>You must have a basedir!</message>
                  <regex>\d</regex>
                  <regexMessage>You must have a digit in your baseDir!</regexMessage>
                </requireProperty>
                <requireProperty>
                  <property>project.version</property>
                  <message>"Project version must be specified."</message>
                  <regex>(\d|-SNAPSHOT)$</regex>
                  <regexMessage>"Project version must end in a number or -SNAPSHOT."</regexMessage>
                </requireProperty>
              </rules>
              <fail>true</fail>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  [...]
</project>
Run Code Online (Sandbox Code Playgroud)


小智 7

您可以将默认值指定为

<properties>
      <someTag>defaultValue</someTag>
</properties>
Run Code Online (Sandbox Code Playgroud)

运行maven命令时,可以像这样覆盖该值

mvn clean package -DsomeTag=newSpecificValue
Run Code Online (Sandbox Code Playgroud)