springboot初始化修改yml文件并加载

package com.lezu.springboot.config;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;

import javax.annotation.PostConstruct;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.Map;

@Component
public class initConfig {

    @PostConstruct
    public void init() {
        Yaml yaml = new Yaml();
        FileWriter fileWriter = null;
        //层级map变量
        Map<String, Object> serverMap, dataSourceMap, resultMap;
        try {
            Resource resource = new ClassPathResource("application-dev.yml");
            String path = resource.getFile().getPath();
            //读取yaml文件,默认返回根目录结构
            resultMap = yaml.load(new FileInputStream(path));
            //get出spring节点数据
            serverMap = (Map<String, Object>) resultMap.get("server");
            serverMap.put("port", "6666");
            //字符输出
            fileWriter = new FileWriter(path);
            //用yaml方法把map结构格式化为yaml文件结构
            fileWriter.write(yaml.dumpAsMap(resultMap));
            //刷新
            fileWriter.flush();
            //关闭流
            fileWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("对不起,yaml文件修改失败!");
        }
    }


}

 端口成功修改为6666并且加载

posted @ 2022-06-14 21:34  难忘是想起  阅读(1)  评论(0)    收藏  举报  来源