您的位置:首页 > 编程语言 > Java开发

Spring 后置处理器 PropertyPlaceholderConfigurer 类(引用外部文件)

2016-12-13 12:02 323 查看
[b]一、PropertyPlaceholderConfigurer类的作用[/b]

PropertyPlaceholderConfigurer 是 BeanFactory 后置处理器的实现,也是 BeanFactoryPostProcessor 接口的一个实现。允许将上下文(配置文件)中的属性值放在另一个单独的标准 JavaProperties 文件中去。在 XML 文件中用类似 EL 表达式的 ${key} 替换指定的 properties 文件中的值。这样的话,以后更改参数时,我们直接替换 properties 文件中的值就可以了。

[b]二、在配置文件中如何使用这个类呢?[/b]

1. 在 Spring 中,使用 PropertiesPlaceholderConfigurer 在 XML 配置文件中引入外部属性文件,还可以指定编码格式。

<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>jdbc.properties</value>
</property>
<property name="fileEncoding">
<value>UTF-8</value>
</property>
</bean>


当有多个属性文件时

<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/db.properties</value>
<!-- 注意这两种value值的写法 -->
<value>classpath: jdbc.properties</value>
</list>
</property>
</bean>


2. 创建标准的 JavaProperties 文件 jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/mysqldb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=round;
jdbc.username=root
jdbc.password=123456


3. 在 Spring 配置文件中使用引入的外部文件中的值

一个简单的数据源:使用 ${} 调用

<bean id="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">
<property name="driverClassName"value="${jdbc.driverClass}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}"/>
<property name="password"value="${jdbc.password}" />
</bean>


PropertyPlaceholderConfigurer 起的作用就是将占位符指向的数据库配置信息放在 bean 中定义的工具。

[b]三、使用时的两点注意事项[/b]

1. PropertyPlaceholderConfigurer 默认在指定的 properties 文件中找不到你需要的属性,它还会在 Java 的 System 类属性中查找。

我们可以通过如下方法给 Spring 配置文件传递参数

System.setProperty(key, value);


这种默认行为也可以通过 systemPropertiesModeName 或者 systemPropertiesModel 参数来改变。

PropertyPlaceholderConfigurer 类为我们提供了三种模式。

SYSTEM_PROPERTIES_MODE_NEVER: 只允许在 properties 文件中查找,不允许去System类中查找。

SYSTEM_PROPERTIES_MODE_FALLBACK: 默认模式。

SYSTEM_PROPERTIES_MODE_OVERRIDE: 优先 System 类中查找,找不到再去 properties 文件中查找,与默认模式正好相反。

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!-- 优先在System类中查找 -->
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="locations">
<list>
<value>classpath*:/jdbc.properties</value>
</list>
</property>
</bean>


2. Spring2.5 以后,引入了简化的引入外部文件的方式,如下:

<context:property-placeholder location="classpath:db.properties"/>


location 属性定义在 PropertyPlaceholderConfigurer 的祖宗类 PropertiesLoaderSupport 中,并且只有 setter 方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐