java 读取properties配置文件

目录结构:

1. 首先有个一主配置文件:custom.properties,主要用于加载全局的,不区分开发环境的配置,里面必须包含一个属性profiles.active(区分加载哪个配置);

2. 创建一个 custom-xxx.properties 的配置文件,在主配置文件中设置 profiles.active=xxx 即可加载 custom-xxx.properties 的配置,主要用于区分开发环境;

3. Tools.isBlank() 方法可看 https://www.cnblogs.com/lixingwu/p/7113591.html ;

4. 使用方法可查看main方法。

package com.zhwlt.logistics.utils;


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

/**
 * 读取properties文件
 *
 * @author lixingwu
 */
public class PropertiesUtils {
    private Properties properties;
    private Properties propertiesCustom;
    private static PropertiesUtils propertiesUtils = new PropertiesUtils();

    /**
     * 私有构造,禁止直接创建
     */
    private PropertiesUtils() {
        // 读取配置启用的配置文件名
        properties = new Properties();
        propertiesCustom = new Properties();
        InputStream in = PropertiesUtils.class.getClassLoader().getResourceAsStream("custom.properties");
        try {
            properties.load(in);
            // 加载启用的配置
            String property = properties.getProperty("profiles.active");
            if (!Tools.isBlank(property)) {
                InputStream cin = PropertiesUtils.class.getClassLoader().getResourceAsStream("custom-" + property + ".properties");
                propertiesCustom.load(cin);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取单例
     *
     * @return PropertiesUtils
     */
    public static PropertiesUtils getInstance() {
        if (propertiesUtils == null) {
            propertiesUtils = new PropertiesUtils();
        }
        return propertiesUtils;
    }

    /**
     * 根据属性名读取值
     * 先去主配置查询,如果查询不到,就去启用配置查询
     *
     * @param name 名称
     */
    public String getProperty(String name) {
        String val = properties.getProperty(name);
        if (Tools.isBlank(val)) {
            val = propertiesCustom.getProperty(name);
        }
        return val;
    }
public static void main(String[] args) {
        PropertiesUtils pro = PropertiesUtils.getInstance();
        String value = pro.getProperty("custom.properties.name");
        System.out.println(value);
    }
}

 

posted @ 2018-07-01 00:00  喵喵扑  阅读(1550)  评论(0编辑  收藏  举报