Spring boot loads the custom yml file, springyml

Source: Internet
Author: User

Spring boot loads the custom yml file, springyml

The configuration file in yml format is very user-friendly, so I want to put it in the project. replace all properties. yml file. It hurts to remove the location parameter in @ configurationProperties after springboot 1.5. After various queries, you can use YamlPropertySourceLoader to load the yml file and run the code on it.


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

Here we mainly implement the ApplicationListener <ApplicationEnvironmentPreparedEvent> interface of spring boot. spring boot provides us with four kinds of listening events:

1. events triggered when ApplicationStartedEvent spring boot is started

2. ApplicationEnvironemntPreparedEvent spring boot is triggered when Environment is loaded but applicationContext is not started yet (it is different from EnvironmentAware, which is called only after Bean is loaded)

3. ApplicationPreparedEvent springboot completes context creation. bean loading is not complete yet.

4. triggered when ApplicationFailedEvent spring boot startup exception occurs.

Spring boot has a lot of listener internally. They listen to the above events separately and will not go into details here. If you are interested, you can study the source code of spring boot.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.