在属性文件中定义为 ${...} 的 Maven 变量未转换为实际值

Maven variables defined as ${...} in properties file not transformed to real value

我遵循了解释如何过滤资源并将所有变量及其值放在单独的属性文件中的 Maven 文档,这样我就不必每次都重写 pom.xml。参见 link: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"));

        }

测试 class 结果:${index.page} 我期待真正的价值:https://www.test.com/help

有人能解释一下我错过了什么吗?

找到解决方案。我必须将我的属性文件放在 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>