java动态加载配置
参考文章
https://blog.csdn.net/ray_352801250/article/details/81535982
这种加载方法会将config.properties文件加载到内存中,在下次需要读取时直接从内存中获取文件信息,而不是再次读取!
既然以上方法会将文件信息缓存,那么我只要改变一下文件的输入流获取方式就行了。
改成如下方式就行了:
[java] view plain copy
Properties prop = new Properties();
String path = CommonUtils.class.getClassLoader().getResource(“config.properties”).getPath();
InputStream is = new FileInputStream(path);
prop.load(is);
配置文件位置
新建如下加载配置文件的工具类,在其他需要用的配置信息的地方调用工具类方法获取配置参数即可
public class LoadPropertiesutil {
private static final Logger logger = LogManager.getLogger(LoadPropertiesutil.class);
/**
* 加载文件
* *@param fileName为项目根路径下路径
* @return
* */
public static Properties loadProperties(String fileName){
Properties properties = new Properties();
FileInputStream is = null;
try{
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
is = new FileInputStream(path + fileName) ;
properties.load(is);
}catch (Exception e){
logger.error(e.getMessage());
}finally {
if(is!=null){
try{
is.close();
}catch (IOException e){
logger.error(e.getMessage());
}
}
return properties;
}
}
public static String getKey(String fileName, String key){
String result = null;
try{
Properties properties = loadProperties(fileName) ;
result = (String) properties.get(key);
}catch (Exception e){
logger.info("加载配置文件"+fileName+"失败");
logger.error(e.getMessage());
}
return result;
}
}
在调用的地方动态读取
String configTime = LoadPropertiesutil.getKey("./config.properties",“send.sms.msg”);