-
扩展点简述
Strategy interface for creating resource-based {@link PropertySource} wrappers.
定义创建资源的PropertySource包装器的策略接口。
-
扩展点的生命周期及扩展点的执行时机
属于Spring容器创建前,需要先预加载一些属性配置,交由Spring的配置管理器管理,可使用@Value读取。
-
扩展点的作用
主要用来扩展Spring对资源文件的读取,例如:配置文件等。
-
扩展点实战
/**
* 利用Spring自定义的ymal配置读取器
*/
public class YamlPropertySourceFactory implements PropertySourceFactory {
/**
* Create a {@link PropertySource} that wraps the given resource.
*
* @param name the name of the property source
* (can be {@code null} in which case the factory implementation
* will have to generate a name based on the given resource)
* @param resource the resource (potentially encoded) to wrap
* @return the new {@link PropertySource} (never {@code null})
* @throws IOException if resource resolution failed
* @See 解析器 org.springframework.context.annotation.ConfigurationClassParser
*/
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
// 请配置注解参数:ignoreResourceNotFound = true
try {
String filename = Objects.requireNonNull(resource.getResource().getFilename());
//1.创建yaml文件解析工厂
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
//2.设置资源内容
yaml.setResources(resource.getResource());
//3.解析成properties文件
Properties properties = yaml.getObject();
if (properties == null) {
throw new FileNotFoundException();
}
//4.返回符合spring的PropertySource对象
return name != null ? new PropertiesPropertySource(name, properties)
: new PropertiesPropertySource(filename, properties);
} catch (Exception e) {
e.printStackTrace();
throw new IOException("Yaml解析异常,异常原因:" + e.getMessage());
}
}
}
还需要配置一个@PropertySource注解来定义扫描规则:
/**
* 配置文件管理类:
* 1. 默认读取位置为 classpath:application.yml。
* 2. 由 spring管理来自 yml文件读取到的属性,交给 @See {@link YamlPropertySourceFactory} 管理
*/
@Configuration
@PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class)
public class PropertySourceConfig {
}
更多Spring扩展请查看专题Spring开发笔记。