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<String> 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);
      }

    });


  }

这里主要实现了spring boot的ApplicationListener<ApplicationEnvironmentPreparedEvent>接口,spring boot为我们提供了四种监听事件:

1.ApplicationStartedEvent   spring boot 刚启动时会触发事件

2.ApplicationEnvironemntPreparedEvent    spring boot 完成Environment的装载但是还没有开始applicationContext的装载的时候触发(它和实现了EnvironmentAware不一样,后者时需要Bean被装载进去后才调用)

3.ApplicationPreparedEvent   springboot 完成上下文的创建,单还没有完全完成bean的装载

4.ApplicationFailedEvent   spring boot启动异常时触发。

spring boot内部本身就有很多listener,他们分别监听上面几种事件,这里就不再赘述,有兴趣的同学可以研究一下spring boot的源码。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。

新闻名称:springboot装载自定义yml文件
文章URL:https://www.cdcxhl.com/article12/ghpogc.html

成都网站建设公司_创新互联,为您提供网站排名网站建设企业网站制作网站设计自适应网站App开发

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

营销型网站建设