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

Time:03-07

I followed the maven document that explains how to filter resources and put all variables and their values in a separate properties file so that I do not have to rewrite my pom.xml everytime. See link: https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

Added the following to the 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>

My config.dev.properties file:

index.page=https://www.test.com/help

My config.properties file:

index.page=${index.page}

My java file for loading the properties:

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"));

        }

Testing class results in: ${index.page} I was expecting the real value: https://www.test.com/help

Can someone explain me what I am missing?

CodePudding user response:

Found the solution. I had to put my properties files under src/main/resources and NOT src/test/resources. That fixed my issue. In a nutshell:

<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>

I added also:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>3.2.0</version>
        <configuration>
          <propertiesEncoding>UTF-8</propertiesEncoding>
        </configuration>
</plugin>
  • Related