Skip to content
Home » Apache Commons Configurations: An Introduction

Apache Commons Configurations: An Introduction

Managing configurations in a Java application can be quite a challenging task, particularly when you’re dealing with a large codebase or complex system architecture. Fortunately, the Apache Commons Configuration library simplifies this process, providing a way to handle configurations from various sources in a unified manner.

This article will explore how to use the Apache Commons Configuration library to manage configurations in a Java application.

Introduction to Apache Commons Configuration

Apache Commons Configuration is a library developed by the Apache Software Foundation. It provides a generic configuration interface which enables a Java application to read configuration data from a variety of sources.

These sources can include:

  • Properties files
  • XML files
  • Databases
  • Windows INI files
  • Hadoop configuration files
  • System properties
  • and many more

The library also supports various features like Configuration Events, Bean Declarations, Interpolation, Reloading Strategies, and much more.

Setting Up Apache Commons Configuration

Before you can use Apache Commons Configuration, you’ll need to add the library to your project. If you’re using Maven, you can add the following dependency to your pom.xml:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-configuration2</artifactId>
    <version>2.7</version>
</dependency>
XML

Replace the version with the latest available version if it’s newer than 2.7.

Reading Configuration Data

After adding the library to your project, you can start reading configuration data. Here’s an example of how to read data from a properties file:

import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.ex.ConfigurationException;

public class AppConfig {
    public static void main(String[] args) {
        Configurations configs = new Configurations();
        try {
            Configuration config = configs.properties(new File("config.properties"));
            String host = config.getString("db.host");
            int port = config.getInt("db.port");
            // use host and port
        } catch (ConfigurationException cex) {
            // Something went wrong
        }
    }
}
Java

In this example, we’re using the Configurations class to read a properties file named config.properties. We then retrieve the values of db.host and db.port from the file. Note that the keys in the configuration file should not contain spaces.

Writing Configuration Data

You can also write data to a configuration file. Here’s how:

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
import org.apache.commons.configuration2.reloading.PeriodicReloadingTrigger;
import java.util.concurrent.TimeUnit;

public class AppConfig {
    public static void main(String[] args) {
        Configurations configs = new Configurations();
        try {
            // Create a builder for the configuration
            FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
                configs.propertiesBuilder(new File("config.properties"));

            // Get the configuration
            PropertiesConfiguration config = builder.getConfiguration();

            // Modify the configuration
            config.setProperty("db.host", "localhost");
            config.setProperty("db.port", 5432);

            // Save the configuration
            builder.save();

        } catch (ConfigurationException cex) {
            // Something went wrong
        }
    }
}
Java

This example modifies the db.host and db.port properties in the config.properties file and saves the changes.

Combining Configurations using Apache Commons Configuration

One of the greatest features of Apache Commons Configuration is the ability to combine configurations from different sources. This is particularly useful in scenarios where some configuration parameters are stored in a properties file, and others are stored in a different source like an XML file or a database.

Here’s an example of how to combine configurations from different sources:

import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.CompositeConfiguration;

public class AppConfig {
    public static void main(String[] args) {
        Configurations configs = new Configurations();
        try {
            // Load configurations from different sources
            Configuration dbConfig = configs.properties(new File("db.properties"));
            Configuration appConfig = configs.xml(new File("app.xml"));

            // Create a composite configuration
            CompositeConfiguration compositeConfig = new CompositeConfiguration();
            compositeConfig.addConfiguration(dbConfig);
            compositeConfig.addConfiguration(appConfig);

            // Now you can read properties from both configurations
            String host = compositeConfig.getString("db.host");
            String appName = compositeConfig.getString("app.name");

        } catch (ConfigurationException cex) {
            // Something went wrong
        }
    }
}
Java

In this example, we’re creating a CompositeConfiguration that includes a properties file db.properties and an XML file app.xml. We can then retrieve properties from either file as if they were a single configuration.

Listening for Configuration Changes

Apache Commons Configuration also allows you to listen for changes in the configuration. This can be useful in scenarios where you need to react to changes in the configuration, such as reloading resources or updating application settings.

Here’s an example of how to listen for configuration changes:

import org.apache.commons.configuration2.event.ConfigurationEvent;
import org.apache.commons.configuration2.event.ConfigurationListener;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;

public class AppConfig {
    public static void main(String[] args) {
        Configurations configs = new Configurations();
        try {
            FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
                configs.propertiesBuilder(new File("config.properties"));
            PropertiesConfiguration config = builder.getConfiguration();

            // Add a listener for configuration changes
            config.addConfigurationListener(new ConfigurationListener() {
                public void configurationChanged(ConfigurationEvent event) {
                    // Only interested in changes to the configuration
                    if (!event.isBeforeUpdate()) {
                        System.out.println("Configuration changed: " + event.getPropertyName());
                    }
                }
            });

            // Make a change to the configuration
            config.setProperty("db.host", "localhost");

        } catch (ConfigurationException cex) {
            // Something went wrong
        }
    }
}
Java

In this example, we’re adding a listener to the configuration that prints a message whenever a property is changed. The listener is notified both before and after the change, but in this case, we’re only interested in the change after it has occurred.

Conclusion

Apache Commons Configuration is a powerful library that simplifies the management of configurations in Java applications. It provides a unified interface to various configuration sources and supports features like configuration events, combined configurations, and automatic reloading of configuration files. By using this library, you can make your application more flexible and easier to maintain.