如何创建 Maven 配置文件来设置系统 属性

How can I create maven profile to set system property

我需要创建 2 个 Maven 配置文件,我可以在其中设置两个不同的系统属性。这些配置文件仅用于设置系统 属性,与任何插件无关。

喜欢

<profile>
   <id> profile1 to set system property 1</id>
   .... set system property1
</profile>
<profile>
   <id> profile2 to set system property 2</id>
   .... set system property2
</profile>

可以,但这取决于您的需要。这是最常见的做法:

  <profiles>
    <profile>
      <id>profile-1</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>properties-maven-plugin</artifactId>
            <version>1.0-alpha-2</version>
            <executions>
              <execution>
                <goals>
                  <goal>set-system-properties</goal>
                </goals>
                <configuration>
                  <properties>
                    <my-prop>Yabadabadoo!</my-prop>
                  </properties>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

但这只会在 Maven 执行期间设置系统 属性,所以如果您希望(例如)这个 class 获取它:

package org.example;

public class App {
    public static void main( String[] args)      {
        System.out.println("-->" + System.getProperty("my-prop"));
    }
}

你需要 运行 它与 mvn -P profile-1 compile exec:java -Dexec.mainClass=org.example.App 它会产生以下结果:

[INFO] --- exec-maven-plugin:1.4.0:java (default-cli) @ sys-prop ---
-->Yabadabadoo!

运行 它没有 compile 目标会给你一个 null 因为 exec 插件在这种情况下没有绑定到任何构建阶段。

但是如果您需要系统属性来进行(比如)单元测试,那么 surefire 插件就是您所需要的。