Retrieving Typed Configuration with Commons Configuration

Typed configuration is very straightfoward with Commons Configuration. One of my pet peeves is having to translate numeric configuration parameters from String instances to the corresponding primitive type. The following example loads configuration from the file:

       // import the necessary classes...
      import org.apache.commons.configuration.Configuration;
      import org.apache.commons.configuration.ConfigurationFactory;

      // Load your configuration from the classpath...
      Configuration config = new PropertiesConfiguration( "" );
      // Retrieve configuration parameters
      float timeout = config.getFloat("timeout"));
      String region = config.getString("region"));
      String name = config.getString("name"));
      int speed = config.getInt("speed"));

The file has the format of a standard Java properties file, with a key and value on each new line:

      name=This is an Example

If you need to convert to an Object instead of a primitive, you’ll need to supply a default value to be used if the configuration parameters is not available. For example, the following code would set timeout to Float.NaN and speed to 0 if these parameters were not present in the specified properties file.

       Float timeout = config.getFloat( "timeout", Float.NaN );
      Integer speed = config.getInteger( "speed", new Integer( 0 ) );