@Configurationpublic class SetProperties {/*** application.properties加载完毕后执行* @throws IOException*/@PostConstructpublic 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();}}
注:需要每次重启服务,在考虑不损耗资源的情况下,可以使用定时任务
如果觉得《springboot 动态修改配置文件》对你有帮助,请点赞、收藏,并留下你的观点哦!