修改配置文件并实时刷新


这里列出了两种方式推荐第二种

一基于java.util.properties

优缺点:
1.优点在于无需引入额外的jar包
2.但有一个明显的缺点:通过这种方式修改的properties文件,其键值对顺序会乱。并且格式会改变注释没有了
关键代码块:

//注入类
@Autowired
    private ConfigurableWebApplicationContext configurableWebApplicationContext;
@Autowired
	private ServletContext servletContext;
	
Properties properties = new Properties();
//读取配置文件
InputStream input = servletContext.getResourceAsStream("/WEB-INF/application/bec-timetable-monitor.properties");
properties.load(input);
//获取配置文件路径
String path = servletContext.getRealPath("/WEB-INF/application/bec-timetable-monitor.properties");
//设置属性值
properties.setProperty("current.term", "35");
//输出流要放在load后面,否则文件会被覆盖
OutputStream output = new FileOutputStream(path);
properties.store(output, "Update value");
input.close();
output.close();
//重新加载元数据
XmlWebApplicationContext context = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(servletContext);
context.refresh();
//重新load所有bean
configurableWebApplicationContext.refresh();

二基于apache.commons.configuration.PropertiesConfiguration

这种方式不会造成写入的键值对顺序紊乱(配置文件里面参数多的情况下极力推荐),不过需要引入commons-configuration包
关键代码块:

//apache.commons.configuration.PropertiesConfiguration引用
<dependency>
	<groupId>commons-configuration</groupId>
	<artifactId>commons-configuration</artifactId>
	<version>1.10</version>
</dependency>

//更改bec-timetable-monitor.properties配置文件中属性
//获取配置文件路径
String path = servletContext.getRealPath("/WEB-INF/application/bec-timetable-monitor.properties");
PropertiesConfiguration config  = new PropertiesConfiguration(path);
System.out.println(path);
config.setAutoSave(true);
config.setProperty("current.term", "35");
//重新加载配置文件使属性生效
//重新加载元数据
XmlWebApplicationContext context = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(servletContext);
context.refresh();
//重新load所有bean
configurableWebApplicationContext.refresh();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

低调D树苗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值