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

use*_*632 -1 spring maven-3 maven spring-boot

我需要创建 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>
Run Code Online (Sandbox Code Playgroud)

Dan*_*iel 5

可以,但这取决于您需要它的用途。这是最常见的方法:

  <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>
Run Code Online (Sandbox Code Playgroud)

但这仅在 Maven 执行期间设置系统属性,因此如果您希望(例如)此类选择它:

package org.example;

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

你需要运行它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!
Run Code Online (Sandbox Code Playgroud)

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

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