重写 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;
}
});
}
就能通过自定义的方法进行动态配置