spring boot loads the custom yml file

  • 2020-06-23 00:19:55
  • OfStack

The configuration file in yml format feels very humanized, so I want to replace.properties in the project with.yml file. The main springboot has removed the location parameter in @configurationProperties since 1.5


 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 is mainly implemented here < ApplicationEnvironmentPreparedEvent > Interface, spring boot gives us four listening events:

Events are triggered when ApplicationStartedEvent spring boot is first started

2.ApplicationEnvironemntPreparedEvent spring boot has completed the loading of Environment but has not triggered when the loading of applicationContext starts (it is different from the implementation of EnvironmentAware, which requires Bean to be loaded before calling).

3.ApplicationPreparedEvent springboot The context has been created and the loading of bean has not been completed

4.ApplicationFailedEvent spring boot triggered when an exception was started.

spring boot itself has a lot of listener, they are listening to the above several events, it will not be described here, interested students can study 1 spring boot source code.


Related articles: