PropertyPlaceholderConfigurer位于org.springframework.beans.factory.config 包下,它的继承体系如下

PropertyPlaceholderConfigurer 直接继承于PlaceholderConfigurerSupport,它的已知实现类只有一个PreferencesPlaceholderConfigurer。
源自JavaDoc: PropertyPlaceholderConfigurer 是 PlaceholderConfigurerSupport 的一个子类,用来解析${…} 占位符的,可以使用setLocation和setProperties设置系统属性和环境变量。从Spring3.1 开始,PropertySourcesPlaceholderConfigurer应优先与此实现,通过使用Spring3.1 中的 Environment和 PropertySource机制, 使它的灵活性更强。
但是PropertyPlaceholderConfigurer却适用如下情况:当 spring-context 模块不可用的时候,使用BeanFactory的API 而不是ApplicationContext的API。现有配置使用setSystemPropertiesMode 和 setSystemPropertiesModeName属性,建议用户不要使用这些设置, 而是使用容器的Environment属性;
在Spring3.1 之前,context:property-placeholder/命名空间保存了PropertyPlaceholderConfigurer的实例,如果使用spring-context-3.0 xsd的定义的话,仍然会这样做。也就是说,即使使用Spring 3.1,您也可以通过命名空间保留PropertyPlaceholderConfigurer; 只是不更新schemaLocation 并继续使用3.0 XSD。
PropertyPlaceholderConfigurer 引入外部属性文件
定义一个properties 属性文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sys
jdbc.username=root
jdbc.password=123456
这是一个最基本的配置数据库连接的设置,前缀统一使用jdbc来命名
定义xml用来获取上面properties中的内容
database.properties
通过给PropertyPlaceholderConfigurer 设置一个bean,指定的名称为location,指定value值就能够引入外部配置文件,然后就能够通过${jdbc.key} 来获取properties 中的值
PropertyPlaceholderConfigurer 引入多个属性文件
再来定义一个encoding.properties
file.encoding=utf-8
file.name=encoding
PropertyPlaceholderConfigurer 引入多个属性文件比较简单,需要把location -> locations ,然后直接指定一个list 就能够引入
database.properties encoding.properties
PropertyPlaceholderConfigurer 的替代方案
正如PropertyPlaceholderConfigurer基本概念中提到的,Spring可以使用context:property-placeholder/ 作为PropertyPlaceholderConfigurer 的替代方案,代码如下
自定义一个SubPropertyPlaceholderConfigurer 继承自PropertyPlaceholderConfigurer
public class SubPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {private static Map ctxPropertiesMap;@Overrideprotected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {// 调用父类PropertyPlaceholderConfigurer 的构造器super.processProperties(beanFactoryToProcess, props);// 遍历配置文件的key,Properties 对象就是导入的配置文件Enumeration> enumeration = props.propertyNames();while (enumeration.hasMoreElements()) {System.out.println(enumeration.nextElement());}ctxPropertiesMap = new HashMap();for (Object key : props.keySet()) {String keyStr = key.toString();String value = props.getProperty(keyStr);ctxPropertiesMap.put(keyStr, value);}}public static String getProperty(String name){return ctxPropertiesMap.get(name);}}
需要引入这个自定义的SubPropertyPlaceholderConfigurer
database.properties
如何启动呢?其实引入的SubPropertyPlaceholderConfigurer 就能够随着Spring加载配置文件而被加载。
直接定义main方法,用ClassPathXmlApplicayionContext引入任意的配置文件即可。