根据其他属性的存在设置 Maven 属性

Setting maven properties depending on the presence of other properties

我有一个 Maven 属性 问题,我在文档中找不到提及。 从命令行我将输入 属性 "from.command"。这个 属性 将永远存在。

mvn deploy -Dfrom.command=COMMANDVALUE

在pom.xml里面我会指定另一个属性:

  <properties>
    <from.pom>POMVALUE</from.pom>
  </properties>

这个 属性 有时会出现,有时会丢失。

我想要第三个 属性 命名为 used.value

如果 属性 存在,我希望将 used.value 设置为 "from.pom" 的值,否则应将其设置为 "from.command"[=12 的值=]

出现这种需要是因为我需要 运行 从另一个脚本构建 maven 并且我不希望脚本必须检查所有 pom 文件。

这可能吗?

你可以使用 build-helper-maven-plugin:bsh-property mojo。

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>build-helper-maven-plugin</artifactId>
  <version>1.10</version>
  <executions>
    <execution>
      <id>bsh-property</id>
      <goals>
        <goal>bsh-property</goal>
      </goals>
      <configuration>
        <properties>
          <property>used.value</property>
        </properties>
        <source>
          used.value = project.getProperties().getProperty("from.pom", session.getUserProperties().getProperty("from.command"));
        </source>
      </configuration>
    </execution>
  </executions>
</plugin>

此目标可以编写 BeanShell 脚本。它自动将变量 project 定义为实际的 Maven 项目,将 session 定义为正在执行的 Maven 会话。

上面的脚本从Maven项目的属性中获取属性 "from.pom",默认为命令行设置的"from.command" 属性。它将它设置为 used.value 变量,然后在执行脚本后由插件将其导出为 Maven 属性。使用 getUserProperties():

从 Maven 会话中检索命令行属性

The user properties have been configured directly by the user on his discretion, e.g. via the -Dkey=value parameter on the command line.

此目标自动绑定到 validate 阶段,这是默认生命周期中 运行 的第一个阶段,因此您将能够使用 ${used.value} 作为 属性 在构建的其余部分中。