优先级小于本地配置 来源自定义属性源工厂,即调用的应用会覆盖整个配置
这个用法可以保证以下代码起作用,因为bean加载前加载配置
@ConfigurationProperties(prefix = "parentfw.httpclient.poolmanager")
@Configuration
@EnableConfigurationProperties(HttpclientProperties.class)
@ConditionalOnProperty(prefix = "parentfw.httpclient", value = "enabled", havingValue = "true")
@Configuration
@PropertySource(value = "classpath:application-framework-httpclient.yml", name = "application-framework-httpclient",
factory = FrameworkPropertySourceFactory.class)
public class HttpclientConfigLoader {}
/**
* 用法: <br>
* PropertySourceFactory的加载时机早于Spring Beans容器所以独立加载用于参数入spring环境,优先级低于application.yml <br>
* 根据name属性添加一个<br>
* 以下是@实例<br>
* Configuration <br>
* PropertySource(value = "classpath:application-framework-httpclient.yml", name =
* "application-framework-httpclient", factory =FrameworkPropertySourceFactory.class)
*/
public class FrameworkPropertySourceFactory implements PropertySourceFactory {
/**
*
* @param name
* PropertySource 中的name
* @param encodedResource
* PropertySource 中的value
* @return
* @throws IOException
*/
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
Resource resource = encodedResource.getResource();
String value = resource.getFilename();
if (!resource.exists()) {
CoreLogUtils
.serviceLog("FrameworkPropertySourceFactory加载配置文件失败[资源不存在尝试name][name]" + name + "[value]" + value);
if (null != name && !name.isEmpty()) {
try {
DefaultResourceLoader defaultResourceLoader = new DefaultResourceLoader();
resource = defaultResourceLoader.getResource(name);
} catch (Exception ex) {
CoreLogUtils.errorLog("FrameworkPropertySourceFactory加载配置文件失败[name]" + name + "[value]" + value,
ex);
return replaceNull(name);
}
}
if (!resource.exists()) {
CoreLogUtils.errorLog("FrameworkPropertySourceFactory加载配置文件失败[资源不存在][name]" + name + "[value]" + value);
return replaceNull(name);
}
}
String fileName = resource.getFilename();
try {
List<PropertySource<?>> list = new ArrayList<>();
if (fileName.endsWith(".yml")) {
YamlPropertySourceLoader ymlLoader = new YamlPropertySourceLoader();
list = ymlLoader.load(name, resource);
} else if (fileName.endsWith(".properties")) {
PropertiesPropertySourceLoader propertiesLoader = new PropertiesPropertySourceLoader();
list = propertiesLoader.load(name, resource);
}
if (list.isEmpty()) {
return replaceNull(name);
}
return list.get(0);
} catch (Throwable e) {
CoreLogUtils.errorLog(
"FrameworkPropertySourceFactory加载配置文件失败[异常][name]" + name + "[value]" + resource.getFilename(), e);
return replaceNull(name);
}
}
/**
* 单个jar配置不起作用时不保存,打印异常日志
*
* @param name
* @return
*/
private PropertySource<?> replaceNull(String name) {
return new PropertySource<Object>(name) {
@Override
public Object getProperty(String s) {
return null;
}
};
}
}