How to create a singleton class

As per the comment on your question:

I’ve a properties file containing some keys value pairs, which is need across the application, that is why I was thinking about a singleton class. This class will load the properties from a file and keep it and you can use it from anywhere in the application

Don’t use a singleton. You apparently don’t need one-time lazy initialization (that’s where a singleton is all about). You want one-time direct initialization. Just make it static and load it in a static initializer.

E.g.

public class Config {

    private static final Properties PROPERTIES = new Properties();

    static {
        try {
            PROPERTIES.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
        } catch (IOException e) {
            throw new ExceptionInInitializerError("Loading config file failed.", e);
        }
    }

    public static String getProperty(String key) {
        return PROPERTIES.getProperty(key);
    }

    // ...
}

Leave a Comment