项目中动态操作配置文件

问题描述:

一般的项目当中如果要是修改配置文件则需要重启 服务才能生效,有没有什么办法可以动态的去读取配置文件?

解决方法:

使用  org.springframework.core.io.support.PropertiesLoaderUtils 中的 PropertiesLoaderUtils则可以实现动态读取配置文件,代码示例如下:

PropertiesLoaderUtils.loadAllProperties("constant.properties").get("key")

通过该方法则可以动态读取配置文件中的内容,并不需要重新启动服务器。

下面的代码示例是如何获取指定配置文件的路径,以后的配置文件可以通过请求访问的形式来进行修改,而不必再登录到对应的服务器找到指定的文件来进行修。

修改配置文件数据的代码示例如下:

String filePath = PropertiesUtil.class.getClassLoader().getResource(fileName).getFile();
filePath = URLDecoder.decode(filePath, "utf-8");
Properties props = PropertiesLoaderUtils.loadProperties(new ClassPathResource(fileName));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
props.setProperty("key", "value");
props.store(bw, "");

发布了61 篇原创文章 · 获赞 9 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/u012129030/article/details/102731355