PropertyPlaceholderConfigurer是个bean工厂后置处理器的实现,也就是 BeanFactoryPostProcessor接口的一个实现。PropertyPlaceholderConfigurer可以将上下文(配置文 件)中的属性值放在另一个单独的标准java Properties文件中去。在bean.xml文件中用${key}替换指定的properties文件中的值。这样的话,只需要对properties文件进 行修改,而不用对xml配置文件进行修改。
使用DatabasePlaceholderConfigurer继承PropertyPlaceholderConfigurer,重写loadProperties方法
public class DatabasePlaceholderConfigurer extends
PropertyPlaceholderConfigurer {
private Resource properties;
private DatabasePropertyLoaderStrategy databasePropertyLoaderStrategy;
public DatabasePlaceholderConfigurer() {
super();
}
public DatabasePlaceholderConfigurer(Resource properties,
DatabasePropertyLoaderStrategy databasePropertyLoaderStrategy) {
super();
this.properties = properties;
this.databasePropertyLoaderStrategy = databasePropertyLoaderStrategy;
}
@Override
protected void loadProperties(final Properties props) throws IOException {
logger.trace("entering...");
List<Resource> resources = new ArrayList<Resource>();
if (properties != null) {
resources.add(properties);
}
Resource[] locations = new Resource[resources.size()];
resources.toArray(locations);
setLocations(locations);
super.loadProperties(props);
try {
//读取数据库中配置表的数据,并添加到Properties对象中
databasePropertyLoaderStrategy.loadProperties(props, Boolean.TRUE);
// Set<Entry<Object, Object>> entrySet = props.entrySet();
StringBuffer sb = new StringBuffer();
Enumeration enu = props.propertyNames(); //取出所有的key
while(enu.hasMoreElements()){
//迭代配置
sb.append(enu.nextElement()+"="+props.getProperty((String)enu .nextElement())).append("\n");
}
// for (Entry<Object, Object> entry : entrySet) {
// sb.append(ToStringBuilder.reflectionToString(entry)).append("\n");
// }
//显示如所有配置
logger.debug("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" + sb.toString());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
spring配置文件:
<bean id="databasePlaceholderConfigurer" class="cn.com.xxxx.config.DatabasePlaceholderConfigurer">
<!--constructor-arg:通过构造函数注入。与 property:通过setxx方法注不同--/>
<constructor-arg index="0" value="classpath:resource/application.properties"/>
<!--constructor-arg:通过构造函数注入。与 property:通过setxx方法注不同--/>
<constructor-arg index="1" ref="databasePropertyLoaderStrategy"/>
</bean>
使用:${application.name}即为动态获取的
<bean id="permissionService" class="cn.com.xxxx.service.impl.PermissionServiceImpl">
<property name="applicationName">
<value>${application.name}</value>
</property>
</bean>