@Configuration
public class SetProperties {
/**
* application.properties加载完毕后执行
* @throws IOException
*/
@PostConstruct
public void init() throws IOException {
//文件夹中读取
InputStream inputStream = new FileInputStream("D:/*/*/*/config/my.properties");
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line;
Map<String, Object> map = new HashMap<>();
while ((line = br.readLine()) != null) {
//配置项不等于"" 并且排除注释配置项,并将读取到的配置项转成map集合
if (!line.equals("") && !line.substring(0, 1).equals("#")){
String[] split = line.split("=",2);
if (split.length >0){
map.put(split[0],split[1]);
}
}
}
//配置文件名
String fileName = "application.properties";
//classpath 类路径
String filePath = PropertiesUtil.class.getClassLoader().getResource(fileName).getFile();
filePath = URLDecoder.decode(filePath, "utf-8");
//配置项集合
Properties props = PropertiesLoaderUtils.loadProperties(new ClassPathResource(fileName));
for (Map.Entry<String,Object> entry : map.entrySet()){
//修改相同key的值,值为文件夹map的vlaue
//没有相同的key,会做添加操作
props.setProperty(entry.getKey(), (String) entry.getValue());
}
//写入流
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
props.store(bw, "");
bw.close();
}
}
注:需要每次重启服务,在考虑不损耗资源的情况下,可以使用定时任务