记一次在开发中使用@PropertySource
注解加载yml
文件
背景: 业务需要创建多个配置类,基于 yml
文件拥有简洁的层次结构,遂配置文件选择 yml
类型。 但在实际的开发中遇到使用 @PropertySource
注解无法加载 yml
配置文件问题。
分析过程:
首先我们先来分析一下 @PropertySource
注解的源码:
public @interface PropertySource {
/** 加载资源的名称 */
String name() default "";
/**
* 加载资源的路径,可使用classpath,如:
* "classpath:/config/test.yml"
* 如有多个文件路径放在{}中,使用','号隔开,如:
* {
"classpath:/config/test1.yml","classpath:/config/test2.yml"}
* 除使用classpath外,还可使用文件的地址,如:
* "file:/rest/application.properties"
*/
String[] value();
/** 此属性为根据资源路径找不到文件后是否报错, 默认为是 false */
boolean ignoreResourceNotFound() default false;
/** 此为读取文件的编码, 若配置中有中文建议使用 'utf-8' */
String encoding() default "";
/**
* 关键:此为读取资源文件的工程类, 默认为:
* 'PropertySourceFactory.class'
*/
Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
}
复制代码
从源码可以看出,读取资源文件 PropertySourceFactory
接口是关键,加下来打开 PropertySourceFactory
接口的源码:
public interface PropertySourceFactory {
PropertySource<?> createPropertySource(@Nullable String var1, EncodedResource var2) throws IOException;
}
复制代码
发现其中只有一个创建属性资源接口的方法,接下来我们找到实现这个方法的类:
public class DefaultPropertySourceFactory implements PropertySourceFactory {
public DefaultPropertySourceFactory() {
}
publ