Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use config properties file throughout the classes?

I need my Java app to read the config properties from a file and use them throughout the classes. I'm thinking of a separate class, that would return a map of property_key:property_value for each of the properties in the file. Then I would read the values from this map in other classes. Maybe there are other, more commonly used options?

My properties file is simple and has about 15 entries.

like image 735
Andrii Yurchuk Avatar asked Feb 02 '26 03:02

Andrii Yurchuk


1 Answers

Just use java.util.Properties to load it. It implements Map already. You can load and get hold of the properties statically. Here's an example assuming that you've a config.properties file in the com.example package:

public final class Config {

    private static final Properties properties = new Properties();

    static {
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            properties.load(loader.getResourceAsStream("com/example/config.properties"));
        } catch (IOException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

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

    // ...
}

Which can be used as

String foo = Config.getSetting("foo");
// ...

You could if necessary abstract this implementation away by an interface and get the instance by an abstract factory.

like image 103
BalusC Avatar answered Feb 04 '26 18:02

BalusC