不停服务,动态加载properties资源文件

时间:2023-12-13 17:24:14

系统运行过程中,我们用注解@Value("${****}")可以获取资源文件中的内

容,获取的内容会被存储在spring缓存中,因此如果我们修改了资源文件,要

想读取到修改后的内容,那就必须重启服务才能生效。那么如果想修改资源文

件中的内容,又不想重启服务,那么只能让服务动态加载资源文件,每一次读

取都是最新的内容,不去读缓存,解决方式如下:

利用工具读取资源文件

package com.***.**.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.sinoway.cisp.controller.ApiController; /**
* 获取properties文件内容工具类
*/
public class PropertyUtil { private final static Logger logger = LoggerFactory.getLogger(ApiController.class); public static String getProperty(String key) {
Properties props = new Properties();
InputStream in = null;
String property = null;
try {
// 第一种,通过类加载器进行获取properties文件流
// in = PropertyUtil.class.getClassLoader().getResourceAsStream("Constant.properties");
// 第二种,通过绝对路径进行获取properties文件流
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
in = new FileInputStream(path + "/Constant.properties");
props.load(in); property = props.getProperty(key);
} catch (FileNotFoundException e) {
logger.error("Constant.properties文件未找到");
} catch (IOException e) {
logger.error("出现IOException");
} finally {
try {
if (null != in) {
in.close();
}
} catch (IOException e) {
logger.error("文件流关闭出现异常");
}
}
logger.info("加载资源文件完成...........");
logger.info("文件内容为:" + props);
return property;
}
}

通过工具获取资源文件中的内容,是每次都会重新读取的,以此来达到动态加载资源文件的目的