首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

spring中所配备Bean的後處理方式(轉)

2012-10-20 
spring中所配置Bean的後處理方式(轉)BeanFactoryPostProcessor 接口是对Bean 工厂的后处理操作。 在Spring

spring中所配置Bean的後處理方式(轉)
BeanFactoryPostProcessor 接口是对Bean 工厂的后处理操作。


在Spring 的PropertyPlaceholderConfigurer 类是实现BeanFactoryProcessor 接口中非常有用的类。它用于Spring 从外部属性文件中载入属性,并使用这些属性值替换Spring 配置文件中的占位符变量(${varible})。


Spring 的ApplicationContext 容器可以非常方便的使用PropertyPlaceholderConfigurer,只需通过简单的配置即可使用。

示例:
<bean id="propertyConfigurer" value="jdbc.properties" />
</bean>

如果需要使用多个配置文件可以使用PropertyPlaceholderConfigurer 的locations属性。


具體一點的例子如下:

Spring的框架中为您提供了一个 BeanFactoryPostProcessor 的实作类别: org.springframework.beans.factory.config.PropertyPlaceholderConfigurer。藉由这个类别,您可以将一些组态设定,移出至.properties档案中,如此的安排可以让XML定义档负责系统相关设定,而.properties档可以作为客户根据需求,自定义一些相关的参数。
来看一个Bean定义档的实际例子:

beans-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">

<beans> 
      <bean id="configBean"
encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">

<beans> 
      <bean id="configBean"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName"><value>${driver}</value></property>
    <property name="url"><value>jdbc:${dbname}</value></property>
</bean>而实际的jdbc.propertis文件是
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root
而jdbc.propertis是怎样引用的呢: 将上边一段配置注册在web.xml中就可以了
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-context.xml</param-value>
</context-param>
当然,不要忘了spring的监听器注册
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
这样,一个简单的数据源就设置完毕了。
实际上,PropertyPlaceholderConfigurer起的作用就是将占位符指向的数据库配置信息放在bean中定义
的工具。

热点排行