首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 操作系统 >

Spring 的 BeanPostProcessor接话把现

2013-07-04 
Spring 的 BeanPostProcessor接口实现今天学习了一下Spring的BeanPostProcessor接口,该接口作用是:如果我

Spring 的 BeanPostProcessor接口实现

今天学习了一下Spring的BeanPostProcessor接口,该接口作用是:如果我们需要在Spring容器完成Bean的实例化,配置和其他的初始化后添加一些自己的逻辑处理,我们就可以定义一个或者多个BeanPostProcessor接口的实现。

?

?

下面我们来看一个简单的例子:

?

package?com.spring.test.di;

?

import?org.springframework.beans.BeansException;

import?org.springframework.beans.factory.config.BeanPostProcessor;

?

public?class?BeanPostPrcessorImpl?implements?BeanPostProcessor {

?

????// Bean?实例化之前进行的处理

????public?Object postProcessBeforeInitialization(Object bean, String beanName)

???????????throws?BeansException {

???????System.out.println("对象"?+ beanName +?"开始实例化");

???????return?bean;

????}

?

????// Bean?实例化之后进行的处理

????public?Object postProcessAfterInitialization(Object bean, String beanName)

???????????throws?BeansException {

???????System.out.println("对象"?+ beanName +?"实例化完成");

???????return?bean;

????}

}

?

只要将这个BeanPostProcessor接口的实现定义到容器中就可以了,如下所示:

<bean?class="com.spring.test.di.BeanPostPrcessorImpl"/>

?

测试代码如下:

?

package?com.spring.test.di;

?

import?org.springframework.context.ApplicationContext;

import?org.springframework.context.support.FileSystemXmlApplicationContext;

?

public?class?TestMain {

?

????/**

?????*?@param?args

?????*/

????public?static?void?main(String[] args)?throws?Exception {

?

???????//?得到ApplicationContext对象

???????ApplicationContext ctx =?new?FileSystemXmlApplicationContext(

??????????????"applicationContext.xml");

???????//?得到Bean

???????ctx.getBean("logic");

????}

}

运行以上测试程序,可以看到控制台打印结果:

?

对象logic开始实例化

对象logic实例化完成

?

BeanPostProcessor的作用域是容器级的,它只和所在容器有关。如果你在容器中定义了BeanPostProcessor,它仅仅对此容器中的bean进行后置。它不会对定义在另一个容器中的bean进行任何处理。

?

注意的一点:

BeanFactoryApplicationContext对待bean后置处理器稍有不同。ApplicationContext会自动检测在配置文件中实现了BeanPostProcessor接口的所有bean,并把它们注册为后置处理器,然后在容器创建bean的适当时候调用它。部署一个后置处理器同部署其他的bean并没有什么区别。而使用BeanFactory实现的时候,bean?后置处理器必须通过下面类似的代码显式地去注册:

?

BeanPostPrcessorImpl beanPostProcessor =?new?BeanPostPrcessorImpl();

Resource resource =?new?FileSystemResource("applicationContext.xml");

?

ConfigurableBeanFactory factory =?new?XmlBeanFactory(resource);

?

factory.addBeanPostProcessor(beanPostProcessor);

?

factory.getBean("logic");

热点排行