spring boot装载自定义yml文件
yml格式的配置文件感觉很人性化,所以想把项目中的.properties都替换成.yml文件,主要springboot自1.5以后就把@configurationProperties中的location参数去掉,各种查询之后发现可以用YamlPropertySourceLoader去装载yml文件,上代码
publicvoidonApplicationEvent(ApplicationEnvironmentPreparedEventevent){ ResourceLoaderloader=newDefaultResourceLoader(); YamlPropertySourceLoaderyamlLoader=newYamlPropertySourceLoader(); ListyamlFilePaths=newArrayList<>(); while(true){ StringyamlFilePath=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(IOExceptione){ logger.error("loadpropertyfilefailed!file:"+filePath); thrownewRuntimeException(e); } }); }
这里主要实现了springboot的ApplicationListener
1.ApplicationStartedEvent springboot刚启动时会触发事件
2.ApplicationEnvironemntPreparedEvent springboot完成Environment的装载但是还没有开始applicationContext的装载的时候触发(它和实现了EnvironmentAware不一样,后者时需要Bean被装载进去后才调用)
3.ApplicationPreparedEvent springboot完成上下文的创建,单还没有完全完成bean的装载
4.ApplicationFailedEvent springboot启动异常时触发。
springboot内部本身就有很多listener,他们分别监听上面几种事件,这里就不再赘述,有兴趣的同学可以研究一下springboot的源码。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。