Java – How to load environment configuration

configurationdesignjavaproperties

In Java the typical way of storing configuration is by using property files. So I have several such files, one for each environment type (dev, test, prod, …).

This configuration is needed in different parts of the code base, i.e. in different classes, but in order to avoid duplicating code for opening the right file into a Properties object and then asking for a specific property, I've decided to have a ConfigurationLoader class which loads the file and holds the Properties object in a static variable.

public class ConfigurationLoader {
    static Properties configuration = new Properties().load(new FileReader("/path/to/my/file"));
    public static String getProperty(String propertyName) {
        return configuration.getProperty(propertyName);
    }
}

(This code is broken by an uncaught exception, but the idea is to load the configuration in a static block)

In this way all the configuration is loaded as soon as this class is loaded and it is available to any class by simply using ConfigurationLoader.getProperty(...). Of course it seems best not to load the same property in multiple places and to maybe create different "configuration domain" classes that do the parsing once and for all.

I then have two questions:

  • Is this a good design? In particular, do you see any major drawback in making configuration available globally?
  • What is the best way to specify which environment configuration to load (-D flag, environment variable, …), i.e. which "/path/to/my/file" to use?

Best Answer

I am assuming you are trying this outside of an application container, in a core java application. Or else, property files are not the right way to do it: deployment descriptors, configuration store, etc., is the right answer.

For configuration, the most common idea is to commons config, which allows you to store your configuration as XML/text. It has quite a few features: allows XPath like access of configuration, allows accessing multi-valued configuration element as a list, etc.,.

The least favored of all is the one you have specified. Even that seems to be broken, as it is from a specific relative/absolute path. Ideally, the file should be on classpath, and should be read from SystemClassLoader as InputStream into the Properties.

Hope this helps.