tomcat动态加载properties文件,无需重启

在Java工程中,如果需要使用.properties类型的文件存放某些配置信息时,一般都是将.properties文件放在src目录下,代码一般都是这样写的:

Properties prop = new Properties();
InputStream is =
CommonUtils.class.getClassLoader().getResourceAsStream("config.properties");//假设当前这个方法是在CommonUtils类下面
prop.load(is);

在系统启动之后,config.properties中的key-value信息都可以获取,但是你想改变一下config.properties中的相关配置,但是又不能重启应用,你就会发现,明明已经修改了config.properties文件内容,为什么读出来的信息还是原先的呢?
原来使用
CommonUtils.class.getClassLoader().getResourceAsStream(“config.properties”)

这种加载方法会将config.properties文件加载到内存中,在下次需要读取时直接从内存中获取文件内的配置信息,而不是重新读取配置!

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

或者

Properties prop = new Properties();
String dirPath = Thread.currentThread().getContextClassLoader().getResource("config.properties").getPath();
FileInputStream file = new FileInputStream(dirPath);
prop.load(file);
prop.getProperty(key);//获取某个key的值
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值