PropertyPlaceholderConfiger和PropertyOverrideConfiger

来源:互联网 发布:java 上传文件到http 编辑:程序博客网 时间:2024/06/05 11:10

PropertyPlaceholderConfiger和PropertyOverrideConfiger这两个类都是对Spring的配置信息的操作。他们都是BeanFactoryPostProcessor接口的实现类,Spring也是通过该接口实现了扩展点机制,从而支持“开-闭”原则。
查看springAPI对该接口的说明:允许对Spring管理的bean定义信息定制改变,来调节spring管理的bean的属性值。Spring容器会自动检测到BeanFactoryPostProcessor的实例,并且在任何其他bean生成之前应用他们。
在实际应用中这两个类也应该是十分常用的。下面介绍使用方法:
在使用之前我们先定义个User类,很简单,代码如下:

package com.cp;public class User {private String name;private String password;//-------------------------------------------getters and setters------------public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "name:"+name+" | password:"+password;}}
该类仅仅定义了name和password属性以及相应的getter、setter方法。

1.使用PropertyPlaceholderConfiger
配置文件如下:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><bean id="user" class="com.cp.User"><property name="name" value="${name}"></property><property name="password" value="${password}"></property></bean><bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations" value="classpath:com/cp/user.properties"/></bean></beans>

接下来是配置文件user.properties:

name=zhangsanpassword=helloworld

客户端代码:
public  ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");User u = ctx.getBean("user",User.class);System.out.println(u);
输出:
name:zhangsan | password:helloworld

2.使用PropertyOverrideConfiger
使用该类配置文件必须符合以下规定:
beanName.property=value
例如在该示例中的配置文件:
user.name=zhangsanuser.password=helloworld
那么Spring配置文件如下:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><bean id="user" class="com.cp.User" init-method="init"><property name="name" value="nimei"></property><property name="password" value="nimei"></property></bean><bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer"><property name="locations" value="classpath:com/cp/user.properties"/></bean></beans>
输出:
name:zhangsan | password:helloworld
这个例子很奇怪。明明user的属性在配置文件中都是赋值"hello",却没有输出hello。
其实:

PropertyOverrideConfiger和PropertyPlaceholderConfiger的区别之处是如果在spring配置文件中被PropertyOverrideConfiger管理的bean的属性如果有默认值,那么PropertyOverrideConfiger会将其覆盖。而PropertyPlaceholderConfiger必须使用"${}"才可以。

使用最频繁之处应该是配置dataSource的时候对这个使用最多吧。


原创粉丝点击