springboot装载自定义yml文件-创新互联

yml格式的配置文件感觉很人性化,所以想把项目中的.properties都替换成.yml文件,主要springboot自1.5以后就把@configurationProperties中的location参数去掉,各种查询之后发现可以用YamlPropertySourceLoader去装载yml文件,上代码

十多年专注成都网站制作,成都定制网站,个人网站制作服务,为大家分享网站制作知识、方案,网站设计流程、步骤,成功服务上千家企业。为您提供网站建设,网站制作,网页设计及定制高端网站建设服务,专注于成都定制网站,高端网页制作,对自上料搅拌车等多个行业,拥有丰富的营销推广经验。
 public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
     ResourceLoader loader = new DefaultResourceLoader();
     YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader();
      List yamlFilePaths = new ArrayList<>();

      while(true){


      String yamlFilePath = environment.getProperty("load.yaml["+i+"]");
      if(yamlFilePath==null){
        break;
      }
      i++;
      if("".equals(yamlFilePath)){
        continue;
      }
      yamlFilePaths.add(yamlFilePath);

    }
yamlFilePaths.forEach(filePath->{

      try {
        environment.getPropertySources().addLast(yamlLoader.load(filePath,loader.getResource(filePath),null));
      } catch (IOException e) {
        logger.error("load property file failed!file:" + filePath);
        throw new RuntimeException(e);
      }

    });


  }


文章题目:springboot装载自定义yml文件-创新互联
本文链接:http://ybzwz.com/article/ejshc.html