我使用属性插件解决了这个问题。
属性在 pom 中定义,并写入 my.properties 文件,然后可以从您的 Java 代码访问它们。
在我的例子中是测试代码需要访问这个属性文件,所以在 pom 中属性文件被写入 maven 的 testOutputDirectory:
<configuration>
<outputFile>${project.build.testOutputDirectory}/my.properties</outputFile>
</configuration>
如果您希望应用代码可以访问属性,请使用 outputDirectory:
<configuration>
<outputFile>${project.build.outputDirectory}/my.properties</outputFile>
</configuration>
对于那些寻找更完整示例的人(我花了一些时间才让这个工作,因为我不明白属性标签的命名如何影响在 pom 文件中其他地方检索它们的能力),我的 pom 看起来如下:
<dependencies>
<dependency>
...
</dependency>
</dependencies>
<properties>
<app.env>${app.env}</app.env>
<app.port>${app.port}</app.port>
<app.domain>${app.domain}</app.domain>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>write-project-properties</goal>
</goals>
<configuration>
<outputFile>${project.build.testOutputDirectory}/my.properties</outputFile>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
在命令行上:
mvn clean test -Dapp.env=LOCAL -Dapp.domain=localhost -Dapp.port=9901
因此可以从 Java 代码中访问这些属性:
java.io.InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties");
java.util.Properties properties = new Properties();
properties.load(inputStream);
appPort = properties.getProperty("app.port");
appDomain = properties.getProperty("app.domain");