设置自定义Maven 2属性的默认值

问题描述 投票:57回答:5

我有一个带有插件的Maven pom.xml,我希望能够在命令行上进行控制。一切都运行不错,除非搜索网络一段时间后我无法弄清楚如何设置我的控件属性的默认值:

<plugin>
    ...
    <configuration>
        <param>${myProperty}</param>
    </configuration>
    ...
</plugin>

所以如果我用Maven运行

mvn -DmyProperty=something ...

一切都很好,但我想在没有-DmyProperty=...开关的情况下为myProperty分配一个特定的值。如何才能做到这一点?

maven-2 properties
5个回答
63
投票

您可以在<build>/<properties>中或在如下所示的配置文件中定义属性默认值。当您使用-DmyProperty=anotherValue在命令行上提供属性值时,它将覆盖POM中的定义。也就是说,POM中属性值的所有定义都只设置为属性的默认值。

<profile>
    ...
    <properties>
        <myProperty>defaultValue</myProperty>            
    </properties>
    ...
       <configuration>
          <param>${myProperty}</param>
       </configuration>
    ...
</profile>

36
投票

泰勒的方法很好,但你不需要额外的配置文件。您只需在POM文件中声明属性值即可。

<project>
  ...
  <properties>
    <!-- Sets the location that Apache Cargo will use to install containers when they are downloaded. 
         Executions of the plug-in should append the container name and version to this path. 
         E.g. apache-tomcat-5.5.20 --> 
    <cargo.container.install.dir>${user.home}/.m2/cargo/containers</cargo.container.install.dir> 
  </properties> 
</project>

如果希望每个用户都能够设置自己的默认值,也可以在user settings.xml文件中设置属性。我们使用此方法隐藏CI服务器用于常规开发人员的某些插件的凭据。


26
投票

您可以使用以下内容:

<profile>
    <id>default</id>
    <properties>
        <env>default</env>
        <myProperty>someValue</myProperty>            
    </properties>
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
</profile>

4
投票

@ akostadinov的解决方案非常适用于常见用途...但是如果在依赖解析阶段(mvn pom层次结构处理的早期阶段......)中反应堆组件将使用所需的属性,则应使用配置文件“无激活”测试机制来确保可选的命令行提供的值总是优先于pom.xml中提供的值。而这就是你的pom层次结构。

为此,请在父pom.xml中添加此类配置文件:

 <profiles>
    <profile>
      <id>my.property</id>
      <activation>
        <property>
          <name>!my.property</name>
        </property>
      </activation>
      <properties>
        <my.property>${an.other.property} or a_static_value</my.property>
      </properties>
    </profile>
  </profiles>

1
投票

这可能对你有用:

<profiles>
  <profile>
    <id>default</id>
    <activation>
      <activeByDefault>true</activeByDefault>
    </activation>
    <build>
     <plugin>
       <configuration>
        <param>Foo</param>
       </configuration>
     </plugin>
    </build>
    ...
  </profile>
  <profile>
    <id>notdefault</id>
    ...
     <build>
      <plugin>
        <configuration>
            <param>${myProperty}</param>
        </configuration>
     </plugin>
     </build>
    ...
  </profile>
</profiles>

那样,

mvn clean将使用“foo”作为您的默认参数。如果您需要覆盖,请使用mvn -P notdefault -DmyProperty=something

© www.soinside.com 2019 - 2024. All rights reserved.