Java Web Application Properties

One of the most common application requirements is usually to create a central place where to keep application properties or application settings. These properties are normally settings or general properties that are applied to the application during runtime. A number of options exist, including creating string properties on your application server and accessing them as JNDI resources. However one of the still most practical approaches is to keep a properties config file with a simple propertyName=propertyValue type of structure. The example below is an example of an Application Config class that loads the application properties from a file named config.properties which is stored in the root of the source packages (root package) and hence automatically deployed with the application jar file during the build process.

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

import java.util.logging.Level;

import java.util.logging.Logger;

public class ApplicationConfig {

    private static Properties properties;

    private static ApplicationConfig config;

    static {

        config = new ApplicationConfig();

    }

    private ApplicationConfig ()  {

        try {

            InputStream in =           this.getClass().getClassLoader().getResourceAsStream("config.properties");

            properties = new Properties();

            properties.load(in);

        } catch (IOException ex) {

            Logger.getLogger(ApplicationConfig.class.getName()).log(Level.SEVERE, null, ex);

        }

    }

    public static ApplicationConfig getApplicationConfig () {

            return config;

    }

    public String getProperty (String propName) {

        return properties.getProperty(propName, "Null");

    }      

}

An example config.properties file might contain something like:

applicationTitle=This is my application

An example test client (which might be a servlet, jsp, etc) can use this class as follows:

ApplicationConfig c = ApplicationConfig.getApplicationConfig();
String title = c.getProperty("applicationTitle");

Comments

Briana said…
Thanks for writing this.
I have no words for this great post such a awe-some information i got gathered. Thanks to Author.