我遵循了 maven 檔案,該檔案解釋了如何過濾資源并將所有變數及其值放在單獨的屬性檔案中,這樣我就不必每次都重寫我的 pom.xml。見鏈接:https ://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html
在 pom.xml 中添加了以下內容:
<filters>
<filter>src/test/resources/env/config.dev.properties</filter>
</filters>
<resources>
<resource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
<includes>
<include>*.properties</include>
</includes>
</resource>
</resources>
我的 config.dev.properties 檔案:
index.page=https://www.test.com/help
我的 config.properties 檔案:
index.page=${index.page}
我用于加載屬性的 java 檔案:
public class PropertiesReader {
Properties properties;
public PropertiesReader(String propertyFileName) {
InputStream is = getClass().getClassLoader().getResourceAsStream(propertyFileName);
this.properties = new Properties();
try {
this.properties.load(is);
} catch (IOException e) {
System.out.println("PROPERTIES EXCEPTION >>>>>> NOT LOADING!!!!!!!!!!!!");
e.printStackTrace();
}
}
public String getProperty(String propertyName) {
return this.properties.getProperty(propertyName);
}
public class TestClass {
public static void main(String[] args) {
PropertiesReader app = new PropertiesReader("config.properties");
System.out.println(app.getProperty("index.page"));
}
測驗類結果: ${index.page} 我期待真正的價值:https://www.test.com/help
有人可以解釋一下我錯過了什么嗎?
uj5u.com熱心網友回復:
找到了解決方案。我必須將我的屬性檔案放在 src/main/resources 下,而不是 src/test/resources 下。這解決了我的問題。簡而言之:
<filters>
<filter>src/main/resources/env/config.${env}.properties</filter>
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>*.properties</include>
</includes>
</resource>
</resources>
我還補充說:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<propertiesEncoding>UTF-8</propertiesEncoding>
</configuration>
</plugin>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/439491.html
