Spring源碼解析(十二)-注冊bean銷毀邏輯

Spring版本

5.2.5.RELEASE

源碼解讀

在《Spring源碼解析(八)-創(chuàng)建單例bean》的doCreateBean方法的最后一步,調(diào)用了registerDisposableBeanIfNecessary進(jìn)行了bean的銷毀邏輯的注冊

1 AbstractAutowireCapableBeanFactory#registerDisposableBeanIfNecessary

    protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
        // 獲取訪問控制上下文
        AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
        if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
            if (mbd.isSingleton()) {
                // 單例模式
                // Register a DisposableBean implementation that performs all destruction
                // work for the given bean: DestructionAwareBeanPostProcessors,
                // DisposableBean interface, custom destroy method.
                // 為給定bean注冊一個(gè)可以執(zhí)行包括DestructionAwareBeanPostProcessors、DisposableBean接口,自定義銷毀方法的DisposableBean實(shí)現(xiàn)
                // 往disposableBeans緩存map寫入beanName和DisposableBeanAdapter的映射關(guān)系
                registerDisposableBean(beanName,
                        new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
            }
            else {
                // 其他模式
                // A bean with a custom scope...
                Scope scope = this.scopes.get(mbd.getScope());
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
                }
                // 交由自定義的scope進(jìn)行銷毀邏輯
                scope.registerDestructionCallback(beanName,
                        new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
            }
        }
    }

如果是單例模式,構(gòu)造一個(gè)DisposableBeanAdapter
對象,之后,將<beanName,構(gòu)造出來的DisposableBeanAdapter對象>寫入緩存map
如果是其他模式,則交由scope進(jìn)行銷毀邏輯的處理

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

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