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接口的實現定義到容器中就可以了,如下所示:

<beanclass="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");


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM