需求
今天,工作的时候,我将properties配置文件改成yaml格式,然后再次执行的时候发生了错误,找了半天发现@PropertySource是不支持解析yaml文件的。写这个博客是为了记录下这个问题的解决办法。
定义
@PropertySource注解用于指定资源文件读取的位置,它不仅能读取properties文件,也能读取xml文件,并且通过YAML解析器,配合自定义PropertySourceFactory实现解析YAML文件。
依赖
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.23</version>
</dependency>
实现PropertySourceFactory 接口
/**
* @author banZhuanRen
* @decription 自定义Yaml解析工厂
*/
public class YAMLPropertySourceFactory implements PropertySourceFactory {
@Override
public org.springframework.core.env.PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
//创建一个YAML解析工厂。
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
//设置资源。
factory.setResources(encodedResource.getResource());
//获取解析后的Properties对象
Properties properties = factory.getObject();
//返回。此时不能像默认工厂那样返回ResourcePropertySource对象 ,要返回他的父类PropertiesPropertySource对象。
return name != null ? new PropertiesPropertySource(name, properties) :
new PropertiesPropertySource(encodedResource.getResource().getFilename(),properties);
}
}
添加注解
如上图,就可以解决,@PropertySource不能读取yaml格式文件的问题。
更多
有朋友告诉我:@ImportResource和@ConfigurationProperties(locations={“classpath:myconfig.yaml”})这两种方法也可以解决上述问题,我没有尝试,感兴趣的可以自己尝试一下。