重写PropertySourcesPlaceholderConfigurer 实现自定义配置读取
重写 PropertySourcesPlaceholderConfigurer的postProcessBeanFactory方法 实现 对配置文件中 ${}配置的自定义解析
默认情况下 ${} 是读取本地配置文件的已存在配置 当不存在时 配置为NULL
其中主要的代码是postProcessBeanFactory方法中的 PropertySource 抽象类
if (this.environment != null) {
this.propertySources.addLast(new PropertySource<Environment>("environmentProperties", this.environment) {
@Nullable
public String getProperty(String key) {
return ((Environment)this.source).getProperty(key);
}
});
}
只需要将getProperty的结果单独拿出来进行验证 并 为NULL 的情况下调用自定义的方法获取值 在return出去
if (this.environment != null) {
this.propertySources.addLast(new PropertySource<Environment>("environmentProperties", this.environment) {
@Nullable
public String getProperty(String key) {
String value = ((Environment)this.source).getProperty(key);
//不存在 说明非配置文件本地 配置
if (value == null){
try{
//存在 异步注入延迟 需要手动获取
if (client == null){
client = beanFactory.getBean(AmdClient.class);
}
value = String.valueOf(client.getValue(key));
}catch (Exception e){
logger.error(e.toString());
}
}
return value;
}
});
}
就能通过自定义的方法进行动态配置
版权声明:本文为qq_41595512原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。