开发者

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 开发者_Python百科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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜