使用BeanFactoryPostProcessor——這種姿勢不要用

使用BeanFactoryPostProcessor這種姿勢不要用

前言

在公司內(nèi),Spring基本都是首選的IOC框架,Spring也提供了很多擴展點讓我們介入到容器的生命周期中龙填,例如BeanFactoryPostProcessor氧急、BeanPostProcessor等。今天就記錄下BeanFactoryPostProcessor的一種不正確用法八回。

約定

實例化:instantiation
初始化:initialization

BeanFactoryPostProcessor的作用

首先貼下BeanFactoryPostProcessor的源碼吧

/**
 * Allows for custom modification of an application context's bean definitions,
 * adapting the bean property values of the context's underlying bean factory.
 *
 * <p>Application contexts can auto-detect BeanFactoryPostProcessor beans in
 * their bean definitions and apply them before any other beans get created.
 *
 * <p>Useful for custom config files targeted at system administrators that
 * override bean properties configured in the application context.
 *
 * <p>See PropertyResourceConfigurer and its concrete implementations
 * for out-of-the-box solutions that address such configuration needs.
 *
 * <p>A BeanFactoryPostProcessor may interact with and modify bean
 * definitions, but never bean instances. Doing so may cause premature bean
 * instantiation, violating the container and causing unintended side-effects.
 * If bean instance interaction is required, consider implementing
 * {@link BeanPostProcessor} instead.
 *
 * @author Juergen Hoeller
 * @since 06.07.2003
 * @see BeanPostProcessor
 * @see PropertyResourceConfigurer
 */
public interface BeanFactoryPostProcessor {

    /**
     * Modify the application context's internal bean factory after its standard
     * initialization. All bean definitions will have been loaded, but no beans
     * will have been instantiated yet. This allows for overriding or adding
     * properties even to eager-initializing beans.
     * @param beanFactory the bean factory used by the application context
     * @throws org.springframework.beans.BeansException in case of errors
     */
    void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

首先請一字一句通讀一下doc酷愧,其中兩句話非常重要:

  • BeanFactoryPostProcessor允許使用者修改容器中的bean definitions
  • BeanFactoryPostProcessor可以與bean definitions打交道,但是千萬不要進(jìn)行bean實例化(感覺這里應(yīng)該說的是不要在BeanFactoryPostProcessor進(jìn)行可能觸發(fā)bean實例化的操作)缠诅。這么做可能會導(dǎo)致bean被提前實例化溶浴,會破壞容器造成預(yù)估不到的副作用。如果你需要hack到bean實例化過程滴铅,請考慮使用BeanPostProcessor戳葵。

從doc中可以讀到,BeanFactoryPostProcessor的主要作用是讓你能接觸到bean definitions汉匙,對bean definitions進(jìn)行一定hack拱烁,但是也僅此而已了。絕對不允許在BeanFactoryPostProcessor中觸發(fā)到bean的實例化X洹O纷浴! 為啥呢伤锚,doc說得很清楚but never bean instances. Doing so may cause premature bean instantiation, violating the container and causing unintended side-effects. 下面就列舉錯誤使用造成的兩種典型“副作用”擅笔。

副作用1——使用注解進(jìn)行依賴注入失敗

貼一下示例代碼片段吧。


@Component
public class PrematureBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        Map<String, BBean> map = beanFactory.getBeansOfType(BBean.class);
        for (BBean bBean : map.values()) {
            assert bBean.getABean() == null;
        }
    }
}

@Component("bBean")
public class BBean {

    @Autowired
    private ABean aBean;

    public ABean getABean() {
        return aBean;
    }

}

@Component
public class ABean {

    private String name = "a";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

如上demo所示屯援,在運行后猛们,BBean中被期待注入的ABean最終為null。這是為啥呢狞洋?

貼一段ApplicationContext的啟動代碼吧

        public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            prepareRefresh();

            // Tell the subclass to refresh the internal bean factory.
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // Prepare the bean factory for use in this context.
            prepareBeanFactory(beanFactory);

            try {
                // Allows post-processing of the bean factory in context subclasses.
                postProcessBeanFactory(beanFactory);

                // Invoke factory processors registered as beans in the context.
                invokeBeanFactoryPostProcessors(beanFactory);

                // Register bean processors that intercept bean creation.
                registerBeanPostProcessors(beanFactory);

                // Initialize message source for this context.
                initMessageSource();

                // Initialize event multicaster for this context.
                initApplicationEventMulticaster();

                // Initialize other special beans in specific context subclasses.
                onRefresh();

                // Check for listener beans and register them.
                registerListeners();

                // Instantiate all remaining (non-lazy-init) singletons.
                finishBeanFactoryInitialization(beanFactory);

                // Last step: publish corresponding event.
                finishRefresh();
            }

            catch (BeansException ex) {
                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

                // Reset 'active' flag.
                cancelRefresh(ex);

                // Propagate exception to caller.
                throw ex;
            }
        }
    }

可以看到的是postProcessBeanFactory(beanFactory); 首先invoke了容器中的BeanFactoryPostProcessor實現(xiàn)類弯淘,其中當(dāng)然就包括PrematureBeanFactoryPostProcessor,此時通過beanFactory.getBeansOfType觸發(fā)了bean提前實例化吉懊。按理說庐橙,bean提前實例化也應(yīng)該沒問題的,aBean也應(yīng)該是能夠被注入的呀借嗽!那為啥最終不是這個結(jié)果呢态鳖。讓我們研究下@Resource @AutoWired這種注解是如何注入依賴的,如何起作用的就明白了恶导。@AutoWired起作用依賴AutowiredAnnotationBeanPostProcessor,@Resource依賴CommonAnnotationBeanPostProcessor浆竭,這倆都是BeanPostProcessor的實現(xiàn)。那BeanPostProcessors在何處被spring invoke呢,參見registerBeanPostProcessors(beanFactory);postProcessBeanFactory(beanFactory); 后面被調(diào)用兆蕉,也就是說BBean被觸發(fā)提前初始化的時候羽戒,AutowiredAnnotationBeanPostProcessor還沒有被注冊自然也不會被執(zhí)行到,自然ABean=null虎韵。

PS:如果ABean和BBean都是通過xml的方式配置的則不會有上述問題(因為會執(zhí)行setter setProperty)易稠,但強烈不建議這么做!

副作用2——可能會將ApplicationContext容器啟動過程暴露在多線程之下

“將ApplicationContext容器啟動過程暴露在多線程之下”倒不完全是因為錯誤使用BeanFactoryPostProcessor包蓝,而是錯上加錯驶社。假設(shè)我們發(fā)現(xiàn)在副作用1的場景下aBean無法注入,而將BBean通過如下方式修改

@Component("bBean")
public class BBean implements ApplicationContextAware {

    private ApplicationContext context;

    @Autowired
    private ABean aBean;

    public ABean getABean() {
        return (ABean)context.getBean("aBean");
    }

    @Override
    public String toString() {
        return "BBean{" +
            "aBean=" + aBean +
            '}';
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}

這樣問題就更大了测萎,雖然在大多數(shù)的場景下不會有問題亡电。但是如果BBean是類似于像DTS processer bean或者像是MetaQ的 listener bean情況就非常糟糕了。這種bean一旦被實例化+初始化之后就可以接受請求硅瞧,如果在請求處理代碼中觸發(fā)了Spring bean的實例化過程份乒,則此時的容器會被破壞,結(jié)果是無法預(yù)知的腕唧。而且問題和可能不太容易復(fù)現(xiàn)或辖,因為只有在spring啟動過程中請求進(jìn)來觸發(fā)ABean首次實例化才有可能會發(fā)生錯誤。強烈要求MetaQ listener DTSprocesser等bean依賴容器自身的依賴注入枣接,不要認(rèn)為干擾颂暇;如果實在要用listener or processor 中使用context.getBean("aBean")的方式,那也請做好listener or processor 的生命周期管理但惶,保證在容器徹底起來之后才開始處理請求

總結(jié)

本文列舉了BeanFactoryPostProcessor錯誤使用可能造成的問題耳鸯。認(rèn)真讀doc,共勉膀曾!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末县爬,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子添谊,更是在濱河造成了極大的恐慌捌省,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,509評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件碉钠,死亡現(xiàn)場離奇詭異,居然都是意外死亡卷拘,警方通過查閱死者的電腦和手機喊废,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來栗弟,“玉大人污筷,你說我怎么就攤上這事。” “怎么了瓣蛀?”我有些...
    開封第一講書人閱讀 163,875評論 0 354
  • 文/不壞的土叔 我叫張陵陆蟆,是天一觀的道長。 經(jīng)常有香客問我惋增,道長叠殷,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,441評論 1 293
  • 正文 為了忘掉前任诈皿,我火速辦了婚禮林束,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘稽亏。我一直安慰自己壶冒,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,488評論 6 392
  • 文/花漫 我一把揭開白布截歉。 她就那樣靜靜地躺著胖腾,像睡著了一般。 火紅的嫁衣襯著肌膚如雪瘪松。 梳的紋絲不亂的頭發(fā)上咸作,一...
    開封第一講書人閱讀 51,365評論 1 302
  • 那天,我揣著相機與錄音凉逛,去河邊找鬼性宏。 笑死,一個胖子當(dāng)著我的面吹牛状飞,可吹牛的內(nèi)容都是我干的毫胜。 我是一名探鬼主播,決...
    沈念sama閱讀 40,190評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼诬辈,長吁一口氣:“原來是場噩夢啊……” “哼酵使!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起焙糟,我...
    開封第一講書人閱讀 39,062評論 0 276
  • 序言:老撾萬榮一對情侶失蹤口渔,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后穿撮,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體缺脉,經(jīng)...
    沈念sama閱讀 45,500評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,706評論 3 335
  • 正文 我和宋清朗相戀三年悦穿,在試婚紗的時候發(fā)現(xiàn)自己被綠了攻礼。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,834評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡栗柒,死狀恐怖礁扮,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤太伊,帶...
    沈念sama閱讀 35,559評論 5 345
  • 正文 年R本政府宣布雇锡,位于F島的核電站,受9級特大地震影響僚焦,放射性物質(zhì)發(fā)生泄漏锰提。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,167評論 3 328
  • 文/蒙蒙 一叠赐、第九天 我趴在偏房一處隱蔽的房頂上張望欲账。 院中可真熱鬧,春花似錦芭概、人聲如沸赛不。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽踢故。三九已至,卻和暖如春惹苗,著一層夾襖步出監(jiān)牢的瞬間殿较,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評論 1 269
  • 我被黑心中介騙來泰國打工桩蓉, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留淋纲,地道東北人。 一個月前我還...
    沈念sama閱讀 47,958評論 2 370
  • 正文 我出身青樓院究,卻偏偏與公主長得像洽瞬,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子业汰,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,779評論 2 354

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理伙窃,服務(wù)發(fā)現(xiàn),斷路器样漆,智...
    卡卡羅2017閱讀 134,654評論 18 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,810評論 6 342
  • 什么是Spring Spring是一個開源的Java EE開發(fā)框架为障。Spring框架的核心功能可以應(yīng)用在任何Jav...
    jemmm閱讀 16,462評論 1 133
  • 2018.1.9 英語:今天是晚上回家完成的》潘睿看來時間擠一擠鳍怨,合理安排一下,孩子配合一下跪妥,還是可以的京景。但這種情況不...
    灸灸微笑閱讀 208評論 0 0
  • 德國國際項目咨詢公司(以下簡稱 IPC 公司)是一家專門為以微小企業(yè)貸款業(yè)務(wù)為主的銀行提供一體化咨詢服務(wù)(即傳統(tǒng)的...
    東伯利亞閱讀 15,721評論 2 23