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.