如何从硬编码的静态配置文件切换到.properties文件? [英] How to switch from a hardcoded static config file to a .properties file?

查看:98
本文介绍了如何从硬编码的静态配置文件切换到.properties文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码使用了一个包含大量硬编码常量的类。这就是它的样子:

I have some code that uses a class holding a huge lot of hardcoded constans. This is what it looks like:

class Constants{
    public static final String name1 = "value1";
    public static final String name2 = "value2";
    public static final Integer value3 = 3;
    ... and so on
}

这些常数用于各处代码如 Constants.name1

These constants are used everywhere in the code like Constants.name1.

我现在需要做的是可以指定值这些常量在配置文件中,可能是 *。properties 文件。

What I need to do now is to make it possible to specify values for these constants in a configuration file, probably a *.properties file.

我的问题是:什么是最好的这样做的方法,不得不重写尽可能少的代码?

My question is: what is the best way to do it, having to rewrite as little code as possible?

我想过使用一个配置类,它在实例化时从文件中读取属性,但是我会必须将值的所有静态调用替换为对该类的实例的调用,并且我将不得不改变现有方法以将此配置实例传递给它们。有更好的方法吗?

I thought of using a single configuration class which reads properties from file when instantiated, but then I'll have to replace all the static calls of values to calls to an instance of that class and I'll have to alter existing methods to pass this config instance into them. Is there a better way?

推荐答案

这是我过去使用的一段代码 - 可以适应你的例子:

Here is a piece of a code I have used in the past - that can be adapted to your example:

public enum Configuration {

    PROPERTY1("property1.name", "default_value_1"),
    PROPERTY2("property2.name", "default_value_2");

    private final String key;
    private String defaultValue;

    Configuration(String key) {
        this(key, NA);
    }

    Configuration(String key, String defaultValue) {
        this.key = key;
        this.defaultValue = defaultValue;
    }
    private final static Logger logger = LoggerFactory.getLogger(Configuration.class);
    private final static String NA = "n.a.";
    private final static String CONFIG_FILE = "properties/config.properties";
    private final static String NOT_A_VALID_KEY = "Not a valid property key";
    private final static Map<Configuration, String> configuration = new EnumMap<>(Configuration.class);

    static {
        readConfigurationFrom(CONFIG_FILE);
    }

    private static void readConfigurationFrom(String fileName) {
        logger.info("Reading resource: {}", fileName);
        try (InputStream resource = Configuration.class.getClassLoader().getResourceAsStream(fileName);) {
            Properties properties = new Properties();
            properties.load(resource); //throws a NPE if resource not founds
            for (String key : properties.stringPropertyNames()) {
                configuration.put(getConfigurationKey(key), properties.getProperty(key));
            }
        } catch (IllegalArgumentException | IOException | NullPointerException e) {
            logger.error("Error while reading the properties file {}", fileName, e);
            populateDefaultValues();
        }
    }

    private static Configuration getConfigurationKey(String key) {
        for (Configuration c : values()) {
            if (c.key.equals(key)) {
                return c;
            }
        }
        throw new IllegalArgumentException(NOT_A_VALID_KEY + ": " + key);
    }

    private static void populateDefaultValues() {
        for (Configuration c : values()) {
            configuration.put(c, c.defaultValue);
        }
    }

    /**
     * @return the property corresponding to the key or null if not found
     */
    public String get() {
        return configuration.get(this);
    }
}

这篇关于如何从硬编码的静态配置文件切换到.properties文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆