Search code examples
apache-commonsapache-commons-config

Combining configuration files


I'm developing a jee application which has to look at two files in order to load configuration parameters. Both files are properties-like files.

The first one contains a default configuration properties and the other one overrides them. So the first one is read-only and the other one can be modified. I need to react and update changes made on second configuration file.

I've take a look on several resources:

I've not been able to figure out what and how to make configuration strategy with commons-configuration2.

Up to now, I've been able to read from one configuration file:

FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
    new FileBasedConfigurationBuilder<PropertiesConfiguration>(PropertiesConfiguration.class)
        .configure(new Parameters().properties()
            .setFileName(ConfigurationResources.PROPERTIES_FILEPATH)
            .setThrowExceptionOnMissing(true)
            .setListDelimiterHandler(new DefaultListDelimiterHandler(';'))
            .setIncludesAllowed(false));

Any ideas?


Solution

  • You need CombinedConfiguration. Here is the sample code

    Parameters params = new Parameters();
    CombinedConfigurationBuilder builder = new CombinedConfigurationBuilder()
        .configure(params.fileBased().setFile(new File("configuration.xml")));
    CombinedConfiguration cc = builder.getConfiguration();
    

    Here configuration.xml file would contain the list of property files

    <configuration systemProperties="systemProperties.xml">
      <!-- Load the system properties -->
      <system/>
      <!-- Now load the config file, using a system property as file name -->
      <properties fileName="myprops1.properties"/>
    
      <properties fileName="myprops2.propert"/>
    </configuration>
    

    This documentation on Combined Configuration will be really helpful