使用@PropertySource默认加载的是.xml或者 .properties文件,因为在注解源码默认使用的是DefaultPropertySourceFactory实现处理文件内容,spring
使用ResourcePropertySource从Resource构建Properties传给Spring。
系统的应用,比如加载自定义的文件,将配置文件内容存储在内存,如下:
那么加载一个自定义的.yml文件,就需要自定义实现ResourcePropertySource来处理yml文件的类,
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}