2

What I am trying to do is the exact same thing as this question : Using Class.getResourcesAsStream to get Apache Commons Configuration but using Apache Commons Configuration 2.

So far, I have tried to make a first maven project with test.properties like this in classpath :

test1=value1

Then, I made an other maven project with another test.properties like this in classpath :

test2=value2

In the second project, I put a dependency on the first one and I create a main in which I put :

public static void main(String[] args) throws Exception {

    Configurations configurations = new Configurations();
    PropertiesConfiguration configuration = configurations.properties("test.properties");
    System.out.println(configuration.getString("test1"));

}

When I run the main, I want to get value1 but I get null. Obviously the way I create the PropertiesConfiguration does not read the test.properties file present in the first module.

Any idea or suggestion to achieve this ?

Community
  • 1
  • 1
pwillemet
  • 613
  • 5
  • 21

1 Answers1

2

I managed to do this by getting the URL with getClassLoader().getResources("...") and then iterating over those URL to load properties files and put them in a CompositeConfiguration.

Still, I wish Apache Commons Configuration2 handled this use case directly.

Maybe a prettier way exists ?

public static void main(String[] args) throws Exception {

    Configurations configurations = new Configurations();
    CompositeConfiguration compositeConfiguration = new CompositeConfiguration();

    Enumeration<URL> urls = ConfigurationTest2.class.getClassLoader().getResources("test.properties");
    while(urls.hasMoreElements()) {
        PropertiesConfiguration propertiesConfiguration = configurations.properties(urls.nextElement());
        compositeConfiguration.addConfiguration(propertiesConfiguration);
    }
    System.out.println(compositeConfiguration.getString("test1"));

}
pwillemet
  • 613
  • 5
  • 21