spring BeanPostProcessor接口

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/DADADIE/article/details/78362845
问题:

如果我们需要在Spring容器完成Bean的实例化、配置和其它初始化后添加一些自己的逻辑处理,我们可以通过定义BeanPostProcessor接口实现。


解决:


package com.spring.supersoft.guanstudy;


public class BeanPostProcessorImpl implements BeanPostProcessor {

 

    public Object postProcessBeforeInitialization(Object bean, String beanName)

           throws BeansException {

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

       return bean;

    }

 

    public Object postProcessAfterInitialization(Object bean, String beanName)

           throws BeansException {

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

       return bean;

    }

}


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

<bean class="com.spring.supersoft.guanstudy.BeanPostProcessorImpl"/>


测试代码如下:


public class Launcher {

 

    /**

     * @param args

     */

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

 

       // 得到ApplicationContext对象

       ApplicationContext ctx = new FileSystemXmlApplicationContext(

              "applicationContext.xml");

       // 得到Bean

       ctx.getBean("good");

    }

}

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

 

对象good开始实例化

对象good实例化完成


原理剖析:

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

另外,BeanFactory和ApplicationContext对BeanPostProcessor处理不同;
ApplicationContext会自动检测在配置文件中实现了BeanPostProcessor接口的所有bean,并把它们注册为后置处理器,然后在容器创建bean的适当时候调用它;
部署一个BeanPostProcessor和部署其他普通bean没什么区别,只需要配置到xml文件中,如:(<bean class="com.spring.supersoft.guanstudy.BeanPostProcessorImpl"/>);
而使用BeanFactory实现的时候,BeanPostProcessor必须通过下面类似的代码显式地去注册:

BeanPostProcessorImpl beanPostProcessorImpl = new BeanPostProcessorImpl();

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

ConfigurableBeanFactory factory = new XmlBeanFactory(resource);

factory.addBeanPostPostProcessor(beanPostProcessorImpl);

factory.getBean("good");



猜你喜欢

转载自blog.csdn.net/DADADIE/article/details/78362845
今日推荐