如何在整个类中使用配置属性文件?

And*_*huk 3 java properties

我需要我的Java应用程序从文件中读取配置属性并在整个类中使用它们.我正在考虑一个单独的类,它将返回property_key:property_value文件中每个属性的映射.然后我会在其他类中读取此映射中的值.也许还有其他更常用的选项?

我的属性文件很简单,大约有15个条目.

Bal*_*usC 9

只是java.util.Properties用来加载它.它Map已经实现了.您可以静态加载和获取属性.这是一个例子,假设你config.propertiescom.example包中有一个文件:

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);
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

哪个可以用作

String foo = Config.getSetting("foo");
// ...
Run Code Online (Sandbox Code Playgroud)

如果需要,您可以通过接口抽象此实现,并通过抽象工厂获取实例.