Tôi đã sử dụng plugin thuộc tính để giải quyết vấn đề này.
Các thuộc tính được xác định trong pom và được ghi ra tệp my.properties, nơi chúng có thể được truy cập từ mã Java của bạn.
Trong trường hợp của tôi, đó là mã kiểm tra cần truy cập tệp thuộc tính này, vì vậy trong pom, tệp thuộc tính được ghi vào testOutputDirectory của maven:
<configuration>
<outputFile>${project.build.testOutputDirectory}/my.properties</outputFile>
</configuration>
Sử dụng outputDirectory nếu bạn muốn các thuộc tính có thể truy cập được bằng mã ứng dụng của mình:
<configuration>
<outputFile>${project.build.outputDirectory}/my.properties</outputFile>
</configuration>
Đối với những người đang tìm kiếm một ví dụ đầy đủ hơn (tôi phải mất một chút thời gian để làm cho điều này hoạt động vì tôi không hiểu cách đặt tên của các thẻ thuộc tính ảnh hưởng đến khả năng truy xuất chúng ở nơi khác trong tệp pom), pom của tôi trông như sau:
<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>
Và trên dòng lệnh:
mvn clean test -Dapp.env=LOCAL -Dapp.domain=localhost -Dapp.port=9901
Vì vậy, các thuộc tính này có thể được truy cập từ mã 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");