配置文件信息读取工具类【PropertiesUtils】

目录

工具类

PropertiesUtils

配置文件

custom.properties

custom-dev.properties

调用结果

 


工具类

PropertiesUtils

package utils;

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

/**
 * 〈一句话功能简述〉PropertiesUtils工具类<br>
 * 〈功能详细描述〉依次从主配置文件->启用配置文件中获取配置信息
 *
 * @author 刘斌
 * @date 2020/3/2
 * @see [相关类/方法](可选)
 * @since [产品/模块版本] (可选)
 */
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 (!StringTools.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 (StringTools.isBlank(val)) {
            val = propertiesCustom.getProperty(name);
        }
        return val;
    }

    public static void main(String[] args) {
        PropertiesUtils pro = PropertiesUtils.getInstance();
        String mainProperty = pro.getProperty("custom.properties.main");
        System.out.println(mainProperty);
        System.out.println("================");
        String profileProperty = pro.getProperty("dev.name");
        System.out.println(profileProperty);
    }
}

配置文件

custom.properties

##主配值文件
custom.properties.main=主配置文件

##启用的配置文件
profiles.active=dev

custom-dev.properties

dev.name=启用配置文件

调用结果

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值