美文网首页java 架构师
枚举单例实现配置文件的读取

枚举单例实现配置文件的读取

作者: 技术官 | 来源:发表于2017-06-14 20:21 被阅读0次

使用enum关键字来实现单例模式的好处是可以提供序列化机制,即使是在面对复杂的序列化或者反射攻击的时候也能防止多次实例化。
例如:
1、配置文件 config.properties 中有以下属性:

      test.case = www.baidu.com

2、枚举类关键代码如下:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 
 * @ClassName: PropertiesSingle 
 * @Description: TODO(单例获取配置文件信息) 
 * @author chang.weng 
 * @date 2017年6月13日 下午3:34:35 
 *
 */
public enum PropertiesSingle {
    INSTANCE;
    private volatile Properties configuration = new Properties();
    public void init() {
        //根路径为classpath
        InputStream is = this.getClass().getResourceAsStream("/config/config.properties");
        if (is != null) {
            try {
                this.configuration.clear();
                this.configuration.load(is);
            } catch (IOException e) {
            } finally {
                try {
                    is.close();
                } catch (Throwable t) {}
            }
        }
    }
    public String getConfigValue(String key) {
          return this.configuration.getProperty(key);
    }
}

3、如何调用?

        PropertiesSingle.INSTANCE.init();
        String finalPropertiesStr = PropertiesSingle.INSTANCE.getConfigValue("test.case");
    

4、总结:

简单安全

相关文章

网友评论

    本文标题:枚举单例实现配置文件的读取

    本文链接:https://www.haomeiwen.com/subject/ogeeqxtx.html