Bean后处理器:即当spring容器实例化Bean实例之后进行的增强处理。
容器后处理器:对容器本身进行处理,并总是在容器实例化其他任何Bean之前读取配置文件的元数据并可能修改这些数据。
一、Bean后处理器
实现了BeanPostProcessor接口的类即可作为一个Bean后处理器,以下是一个Bean后处理器的范例
1、编写一个实现了BeanPostProcessor接口的MyBeanPostProcessor类
- package org.meify.core;
 - import org.meify.bean.AuthorBean;
 - import org.springframework.beans.BeansException;
 - import org.springframework.beans.factory.config.BeanPostProcessor;
 - /**
 - * Bean后处理器
 - * 主要负责对容器初始化其他Bean后进行进一步增强处理
 - * 当Spring容器实例化Bean实例之后,就偶会依次调用Bean后处理器的两个方法对实例Bean进行增强处理。
 - * @description
 - * @version 1.0
 - * @author meify 2014-1-3 下午3:56:39
 - */
 - public class MyBeanPostProcessor implements BeanPostProcessor {
 - @Override
 - public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
 - // TODO Auto-generated method stub
 - System.out.println(beanName+"初始化之前进行增强处理。。。");
 - return bean;
 - }
 - @Override
 - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
 - // TODO Auto-generated method stub
 - System.out.println(beanName+"初始化之后进行增强处理。。。");
 - //重新改编author实例的属性值
 - if(beanName.equals("author")||bean instanceof AuthorBean){
 - AuthorBean author=(AuthorBean) bean; //获取要修改的bean对象
 - author.setAddress("辽宁省大连市");
 - }
 - return bean;
 - }
 - }
 
2、在spring配置文件中注册该Bean后处理器
- <!-- 配置bean后置处理器,可以不配置id -->
 - <bean id="beanProcessor" class="org.meify.core.MyBeanPostProcessor"/>
 
至此一个Bean后处理器即完成了
二、容器后处理器
同上,容器后处理器实现的是BeanFactoryPostProcessor接口
1、编写实现了BeanFactoryPostProcessor接口的MyBeanFactoryPostProcessor的容器后处理器
- package org.meify.core;
 - import org.springframework.beans.BeansException;
 - import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
 - import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
 - /**
 - * 容器后处理器
 - * 通常用于对Spring容器进行拓展,并且总是在容器实例化其他任何bean之前读取配置文件的元数据并进行修改
 - * 典型的应用即对数据源的配置,其中url driver user passwd等通常配置在properties文件中并使用属性占位符配置器来“填充”
 - * @description
 - * @version 1.0
 - * @author meify 2014-1-3 下午4:31:12
 - */
 - public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
 - @Override
 - public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException {
 - // TODO Auto-generated method stub
 - System.out.println("对容器进行后处理。。。。");
 - }
 - }
 
 
2、注册容器后处理器
- <!-- 注册容器后处理器 -->
 - <bean id="factoryProcessor" class="org.meify.core.MyBeanFactoryPostProcessor"/>
 
 
这样一个容器后处理器也完成了
最后编写一个测试程序,对以上的两种后处理器进行测试
- package org.meify.test;
 - import org.meify.bean.AuthorBean;
 - import org.springframework.context.ApplicationContext;
 - import org.springframework.context.support.ClassPathXmlApplicationContext;
 - /**
 - * 获取Spring容器并获取bean实例
 - * 以下代码:
 - * 先获取spring容器,再获取实体bean,将Spring接口与代码耦合在一起,造成代码污染。
 - * @description
 - * @version 1.0
 - * @author meify 2014-1-2 下午2:33:48
 - */
 - public class Test01 {
 - public static void main(String[] args) {
 - //ApplicationContext的实例即Spring容器,也称之为Spring上下文
 - ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-config.xml");
 - System.out.println(ctx);
 - AuthorBean author=ctx.getBean("author",AuthorBean.class);
 - //注意,author的初始化时地址为湖北省武穴市,在Bean后处理器中改变为 辽宁省大连市
 - System.out.println("author的地址为:===="+author.getAddress());
 - }
 - }
 
 
控制台输出如下:
- 2014-1-3 16:33:24 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
 - 信息: Loading XML bean definitions from class path resource [spring-config.xml]
 - 对容器进行后处理。。。。
 - 2014-1-3 16:33:24 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
 - 信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@c09554: defining beans [book,author,beanProcessor,factoryProcessor]; root of factory hierarchy
 - org.springframework.context.support.ClassPathXmlApplicationContext@1cb25f1: startup date [Fri Jan 03 16:33:24 CST 2014]; root of context hierarchy
 - author初始化之后进行增强处理。。。
 - 正在执行初始化方法。。。
 - author初始化之前进行增强处理。。。
 - author的地址为:====辽宁省大连市
 
 
接下来介绍两个容器后处理器的范例。
拿之前的Spring管理数据源为例,使用容器后处理器进行改造。
1、属性占位符配置器
- <!-- 数据源配置 -->
 - <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
 - <property name="driverClassName" value="${jdbc.driverClassName}" />
 - <property name="url" value="${jdbc.url}" />
 - <property name="username" value="${jdbc.username}" />
 - <property name="password" value="${jdbc.password}" />
 - <property name="initialSize" value="${jdbc.initialSize}" />
 - <property name="maxActive" value="${jdbc.maxActive}" />
 - <property name="maxIdle" value="${jdbc.maxIdle}" />
 - <property name="minIdle" value="${jdbc.minIdle}" />
 - <property name="removeAbandoned" value="${jdbc.removeAbandoned}" />
 - <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
 - <property name="maxWait" value="${jdbc.maxWait}" />
 - <property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
 - <property name="validationQuery" value="${jdbc.validationQuery}" />
 - <property name="testWhileIdle" value="${jdbc.testWhileIdle}" />
 - <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />
 - <property name="numTestsPerEvictionRun" value="${jdbc.numTestsPerEvictionRun}" />
 - </bean>
 
 
其中属性占位符处理器的注册
- <!-- 注意PropertyPlaceholderConfigurer——属性占位符配置器,
 - 它作为容器的后处理器将properties文件中配置的属性值填到相应的占位符处 -->
 - <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
 - <property name="locations">
 - <list>
 - <value>classpath*:DB.properties</value>
 - </list>
 - </property>
 - </bean>
 
其中数据源配置properties文件内容如下:
- ### MySQL-\u4e3b\u6570\u636e\u5e93 ###
 - jdbc.driverClassName=com.mysql.jdbc.Driver
 - jdbc.url=jdbc:mysql://10.3.17.22:3306/neuonline?autoReconnect=true&useUnicode=true&characterEncoding=utf8
 - jdbc.username=neuonline
 - jdbc.password=neuonline
 - #\u521d\u59cb\u5316\u8fde\u63a5 \u6570\u91cf
 - jdbc.initialSize = 10
 - #\u6700\u5927\u53ef\u7528\u8fde\u63a5\u6570\u91cf
 - jdbc.maxActive = 200
 - #\u6700\u5927\u7a7a\u95f2\u8fde\u63a5
 - jdbc.maxIdle=100
 - #\u6700\u5c0f\u7a7a\u95f2\u8fde\u63a5
 - jdbc.minIdle=50
 - #\u662f\u5426\u81ea\u52a8\u79fb\u9664\u65e0\u6548\u7684\u8fde\u63a5
 - jdbc.removeAbandoned=true
 - #\u79fb\u9664\u65e0\u6548\u7684\u8fde\u63a5 \u8d85\u65f6\u65f6\u95f4(\u4ee5\u79d2\u6570\u4e3a\u5355\u4f4d)
 - jdbc.removeAbandonedTimeout=120
 - #\u8d85\u65f6\u7b49\u5f85\u65f6\u95f4\u4ee5\u6beb\u79d2\u4e3a\u5355\u4f4d 6000\u6beb\u79d2/1000\u7b49\u4e8e60\u79d2
 - jdbc.maxWait=5000
 - #\u662f\u5426\u83b7\u53d6\u8fde\u63a5\u65f6\u8fdb\u884c\u6d4b\u8bd5
 - jdbc.testOnBorrow=true
 - #\u6d4b\u8bd5\u6570\u636e\u5e93\u6b63\u5e38\u4e0e\u5426\u7684\u8bed\u53e5
 - jdbc.validationQuery=SELECT now()
 - #\u6d4b\u8bd5\u7a7a\u95f2\u94fe\u63a5\u662f\u5426\u53ef\u4ee5\u6b63\u5e38\u8bbf\u95ee
 - jdbc.testWhileIdle=true
 - #\u6d4b\u8bd5\u7a7a\u95f2\u94fe\u63a5\u6d4b\u8bd5\u65f6\u95f4\uff08\u6beb\u79d2\uff09\u95f4\u9694
 - jdbc.timeBetweenEvictionRunsMillis=1800000
 - #\u6d4b\u8bd5\u7a7a\u95f2\u94fe\u63a5\u7684\u6570\u91cf\uff08\u540cjdbc.maxActive\u4fdd\u6301\u4e00\u81f4\uff09
 - jdbc.numTestsPerEvictionRun=200
 
 
这样属性占位符配置器会在容器初始化后,任何其他bean实例化之前将数据源中占位处使用properties文件中的属性值替换。
2、重写占位符配置器
将上面 的配置分别进行修改即可,改动部分如下:
- <bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
 - <property name="locations">
 - <list>
 - <value>classpath*:dbconn.properties</value>
 - </list>
 - </property>
 - </bean>
 
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"/>
 
最后编写测试程序测试获取到的数据库连接
- package org.meify.test;
 - import org.springframework.context.ApplicationContext;
 - import org.springframework.context.support.ClassPathXmlApplicationContext;
 - import java.sql.SQLException;
 - import javax.sql.DataSource;
 - /**
 - * 测试获取数据库连接
 - * @description
 - * @version 1.0
 - * @author meify 2014-1-3 下午2:15:20
 - */
 - public class Test03 {
 - public static void main(String[] args) throws SQLException {
 - ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
 - DataSource ds = (DataSource) ctx.getBean("dataSource", DataSource.class);
 - java.sql.Connection conn = ds.getConnection();
 - System.out.println(conn);
 - }
 - }
 
控制台输出:
- 
    
- jdbc:mysql://10.3.17.22:3306/neuonline?autoReconnect=true&useUnicode=true&characterEncoding=utf8, UserName=neuonline@10.1.242.79, MySQL-AB JDBC Driver
 
 
                  
                  
                  
                  
本文介绍了Spring框架中的两种后处理器:Bean后处理器与容器后处理器。Bean后处理器负责在Bean实例化后对其进行增强处理,而容器后处理器则在容器实例化任何Bean前对容器配置进行修改。文中还提供了具体示例,包括如何通过属性占位符配置器实现数据源配置。
          
                    
      
          
                
                
                
                
              
                
                
                
                
                
              
                
                
              
            
                  
					8万+
					
被折叠的  条评论
		 为什么被折叠?
		 
		 
		
    
  
    
  
            


            