Spring中的后置處理器BeanPostProcessor

BeanPostProcessor接口作用:

如果我們想在Spring容器中完成bean實例化、配置以及其他初始化方法前后要添加一些自己邏輯處理。我們需要定義一個或多個BeanPostProcessor接口實現(xiàn)類,然后注冊到Spring IoC容器中。

package com.test.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
 * bean后置處理器
 * @author zss
 *
 */
public class PostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean,
            String beanName) throws BeansException {
        if ("narCodeService".equals(beanName)) {//過濾掉bean實例ID為narCodeService
            return bean;
        }
        System.out.println("后置處理器處理bean=【"+beanName+"】開始");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean,
            String beanName) throws BeansException {
        if ("narCodeService".equals(beanName)) {
            return bean;
        }
        System.out.println("后置處理器處理bean=【"+beanName+"】完畢!");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return bean;
    }

}

注意:接口中兩個方法不能返回null,如果返回null那么在后續(xù)初始化方法將報空指針異?;蛘咄ㄟ^getBean()方法獲取不到bena實例對象
     因為后置處理器從Spring IoC容器中取出bean實例對象沒有再次放回IoC容器中

## BeanPostProcessor API:

public interface BeanPostProcessor {  
  
    /** 
     * Apply this BeanPostProcessor to the given new bean instance <i>before</i> any bean 
     * initialization callbacks (like InitializingBean's {@code afterPropertiesSet} 
     * or a custom init-method). The bean will already be populated with property values.    
     */  
    //實例化、依賴注入完畢,在調(diào)用顯示的初始化之前完成一些定制的初始化任務  
    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;  
  
      
    /** 
     * Apply this BeanPostProcessor to the given new bean instance <i>after</i> any bean 
     * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}   
     * or a custom init-method). The bean will already be populated with property values.       
     */  
    //實例化、依賴注入、初始化完畢時執(zhí)行  
    Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;  
  
}

由API可以看出:
1:后置處理器的postProcessorBeforeInitailization方法是在bean實例化,依賴注入之后及自定義初始化方法(例如:配置文件中bean標簽添加init-method屬性指定Java類中初始化方法、
@PostConstruct注解指定初始化方法,Java類實現(xiàn)InitailztingBean接口)之前調(diào)用
2:后置處理器的postProcessorAfterInitailization方法是在bean實例化、依賴注入及自定義初始化方法之后調(diào)用

注意:
1.BeanFactory和ApplicationContext兩個容器對待bean的后置處理器稍微有些不同。ApplicationContext容器會自動檢測Spring配置文件中那些bean所對應的Java類實現(xiàn)了BeanPostProcessor
接口,并自動把它們注冊為后置處理器。在創(chuàng)建bean過程中調(diào)用它們,所以部署一個后置處理器跟普通的bean沒有什么太大區(qū)別。
2.BeanFactory容器注冊bean后置處理器時必須通過代碼顯示的注冊,在IoC容器繼承體系中的ConfigurableBeanFactory接口中定義了注冊方法

/**  
     * Add a new BeanPostProcessor that will get applied to beans created  
     * by this factory. To be invoked during factory configuration.  
     * <p>Note: Post-processors submitted here will be applied in the order of  
     * registration; any ordering semantics expressed through implementing the  
     * {@link org.springframework.core.Ordered} interface will be ignored. Note  
     * that autodetected post-processors (e.g. as beans in an ApplicationContext)  
     * will always be applied after programmatically registered ones.  
     * @param beanPostProcessor the post-processor to register  
     */    
    void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);

Spring如何調(diào)用多個BeanPostProcessor實現(xiàn)類:

我們可以在Spring配置文件中添加多個BeanPostProcessor(后置處理器)接口實現(xiàn)類,在默認情況下Spring容器會根據(jù)后置處理器的定義順序來依次調(diào)用。
在Spring機制中可以指定后置處理器調(diào)用順序,通過讓BeanPostProcessor接口實現(xiàn)類實現(xiàn)Ordered接口getOrder方法,該方法返回一整數(shù),默認值為 0,優(yōu)先級最高,值越大優(yōu)先級越低

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,711評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,290評論 6 342
  • 什么是Spring Spring是一個開源的Java EE開發(fā)框架。Spring框架的核心功能可以應用在任何Jav...
    jemmm閱讀 16,785評論 1 133
  • 繼續(xù)臨《多寶塔》,念念不忘,必有回響。
    行之_cd閱讀 267評論 0 2

友情鏈接更多精彩內(nèi)容