这里列出了两种方式推荐第二种
一基于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();
4078

被折叠的 条评论
为什么被折叠?



