最近想把应用中的配置全部放到缓存中,以实现spring从缓存中读取jdbc等相关配置,通过对spring配置文件加载方法的了解,目前找到方法如下:
1.继承配置文件类:org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
2.重写方法:mergeProperties();
3.将新增的org.springframework.beans.factory.config.PropertyPlaceholderConfigurer子类配置到配置文件中;
代码分析:
抽象类PropertiesLoaderSupport中mergeProperties()方法会加载所有配置文件,代码如下:
/**
* Return a merged Properties instance containing both the
* loaded properties and properties set on this FactoryBean.
*/
protected Properties mergeProperties() throws IOException {
Properties result = new Properties();
if (this.localOverride) {
// Load properties from file upfront, to let local properties override.
loadProperties(result);
}
if (this.localProperties != null) {
for (Properties localProp : this.localProperties) {
CollectionUtils.mergePropertiesIntoMap(localProp, result);
}
}
if (!this.localOverride) {
// Load properties from file afterwards, to let those properties override.
loadProperties(result);
}
return result;
} 从以上代码可以看到此方法的功能是将所有配置读取到Properties中,然后会在初始化bean、bean内部来使用这些属性,重写此方法后,此方法应有如下功能:
a)加载配置文件中所有属性;
b)加载用户所需的其他属性;
代码如下:
protected Properties mergeProperties() throws IOException {
Properties allProperties = super.mergeProperties();
// add other properties
return allProperties;
} 暂时只找到此方法来加载缓存中的配置,没发现其他方式来实现此功能。
本文探讨了如何通过继承PropertyPlaceholderConfigurer类并重写mergeProperties()方法,将应用配置从文件加载到缓存中,进而实现Spring从缓存中读取JDBC等相关配置的优化策略。
2942

被折叠的 条评论
为什么被折叠?



