2021-08-27

java动态加载配置

参考文章
https://blog.csdn.net/ray_352801250/article/details/81535982

这种加载方法会将config.properties文件加载到内存中,在下次需要读取时直接从内存中获取文件信息,而不是再次读取!
既然以上方法会将文件信息缓存,那么我只要改变一下文件的输入流获取方式就行了。
改成如下方式就行了:
[java] view plain copy

Properties prop = new Properties();
String path = CommonUtils.class.getClassLoader().getResource(“config.properties”).getPath();
InputStream is = new FileInputStream(path);
prop.load(is);

配置文件位置
在这里插入图片描述

新建如下加载配置文件的工具类,在其他需要用的配置信息的地方调用工具类方法获取配置参数即可


public class LoadPropertiesutil {
    private static final Logger logger = LogManager.getLogger(LoadPropertiesutil.class);
    /**
     * 加载文件
     * *@param fileName为项目根路径下路径
     * @return
     * */
    public static Properties loadProperties(String fileName){
        Properties properties = new Properties();
        FileInputStream is = null;
        try{
            String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
            is = new FileInputStream(path + fileName) ;
            properties.load(is);
        }catch (Exception e){
            logger.error(e.getMessage());
        }finally {
            if(is!=null){
                try{
                    is.close();
                }catch (IOException e){
                    logger.error(e.getMessage());

                }
            }
            return properties;
        }
    }

    public static String getKey(String fileName, String key){
        String result = null;
        try{
            Properties properties = loadProperties(fileName) ;
            result = (String) properties.get(key);
        }catch (Exception e){
            logger.info("加载配置文件"+fileName+"失败");
            logger.error(e.getMessage());
        }
        return result;
    }
}

在调用的地方动态读取
String configTime = LoadPropertiesutil.getKey("./config.properties",“send.sms.msg”);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值