PropertyPlaceholderConfigurer 用法
一、PropertyPlaceholderConfigurer 的继承体系
`PropertyPlaceholderConfigurer`位于**org.springframework.beans.factory.config** 包下,它的继承体系如下
PropertyPlaceholderConfigurer 直接继承于PlaceholderConfigurerSupport
,它的已知实现类只有一个
PreferencesPlaceholderConfigurer
二、PropertyPlaceholderConfigurer 的基本概念
源自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 的基本使用
- PropertyPlaceholderConfigurer是个bean工厂后置处理器的实现,也就是
BeanFactoryPostProcessor
接口的一个实现。PropertyPlaceholderConfigurer可以将上下文(配置文 件)中的属性值放在另一个单独的标准java Properties文件中去。在XML文件中用${…}替换指定的properties文件中的值。这样的话,只需要对properties文件进 行修改,而不用对xml配置文件进行修改。 - 在Spring中,使用PropertyPlaceholderConfigurer可以在XML配置文件中加入外部属性文件
PropertyPlaceholderConfigurer 引入外部属性文件
- 定义一个properties 属性文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sys
jdbc.username=root
jdbc.password=123456
这是一个最基本的配置数据库连接的设置,前缀统一使用jdbc来命名
- 定义xml用来获取上面properties中的内容
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>database.properties</value>
</