yml格式的配置文件感觉很人性化,所以想把项目中的.properties都替换成.yml文件,主要springboot自1.5以后就把@configurationProperties中的location参数去掉,各种查询之后发现可以用YamlPropertySourceLoader去装载yml文件,上代码

public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ResourceLoader loader = new DefaultResourceLoader();
YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader();
List 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);
}
});
}