Bean後置處理器 - SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference

来源:https://www.cnblogs.com/elvinle/archive/2020/07/27/13384992.html
-Advertisement-
Play Games

示例 @Component public class IndexA { @Autowired IndexB bbb; public IndexA() { System.out.println("IndexA constructor..."); } public void printf(){ Syst ...


示例

@Component
public class IndexA {

    @Autowired
    IndexB bbb;

    public IndexA() {
        System.out.println("IndexA constructor...");
    }

    public void printf(){
        System.out.println("indexA printf : ");
        System.out.println("indexB --> " + (bbb == null ? null : bbb.getClass().getName()));
    }
}

@Component
public class IndexB {

    @Autowired
    IndexA aaa;

    public IndexB() {
        System.out.println("IndexB constructor...");
    }

    public void printf(){
        System.out.println("indexB printf : ");
        System.out.println("indexA --> " + (aaa == null ? null : aaa.getClass().getName()));
    }
}

@Configuration
@ComponentScan({
         "com.study.ioc.cyc"
})
public class StartConfig {
}

測試代碼:

public static void main(String[] args) {
    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(StartConfig.class);
    IndexA a = ac.getBean(IndexA.class);
    System.out.println("spring's indexA --> " + a.getClass().getName());
    a.printf();
    System.out.println("======================");
    IndexB b = ac.getBean(IndexB.class);
    System.out.println("spring's indexB --> " + b.getClass().getName());
    b.printf();
}

運行結果:

 

 

 對於這種存在迴圈依賴的情況, 其大致過程是這樣的:

1. 實例化 IndexA

2. 對 IndexA 進行屬性註入, 此時發現 屬性 IndexB

3. 實例化 IndexB

4. 對 IndexB 進行屬性註入, 此時又發現了屬性 IndexA

5. 對 IndexA 執行 getSingleton("indexA") (此時, 會調用後置處理器 SmartInstantiationAwareBeanPostProcessor), 拿到 IndexA

6. 回到 IndexB 屬性註入的地方, 然後對 IndexB 進行初始化

7. IndexB 變成了一個 bean, 回到 IndexA 屬性註入的地方, 然後對 IndexA 進行初始化

 

getSingleton的關鍵代碼為:

org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, boolean)

此時, allowEarlyReference = true, 是寫死的

@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    //從map中獲取bean如果不為空直接返回,不再進行初始化工作
    //講道理一個程式員提供的對象這裡一般都是為空的
    //1.先從一級緩存獲取
    Object singletonObject = this.singletonObjects.get(beanName);
    //2.如果沒獲取到, 且 bean 還在創建中時
    if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
        synchronized (this.singletonObjects) {
            //3.再從二級緩存中獲取
            singletonObject = this.earlySingletonObjects.get(beanName);
            //4. 還沒獲取到, 且允許迴圈依賴時
            if (singletonObject == null && allowEarlyReference) {
                //5. 最後從三級緩存中獲取 對象的工廠, 通過 getObject 來獲取對象
                ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                if (singletonFactory != null) {
                    singletonObject = singletonFactory.getObject();
                    this.earlySingletonObjects.put(beanName, singletonObject);
                    this.singletonFactories.remove(beanName);
                }
            }
        }
    }
    return singletonObject;
}

看到這裡, 需要回到

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

看一句關鍵代碼:

boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
        isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
    if (logger.isTraceEnabled()) {
        logger.trace("Eagerly caching bean '" + beanName +
                "' to allow for resolving potential circular references");
    }
    //這裡創建了一個匿名的 ObjectFactory 實現類, 他是一個工廠, 可以用來獲取對象
    //addSingletonFactory中, 將這個工廠放到 singletonFactories 中去了. singletonFactories 是spring的三級緩存
    addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

singletonFactory.getObject() 調用的, 其實是 這裡的 getEarlyBeanReference() 方法

protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
    Object exposedObject = bean;
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
            }
        }
    }
    return exposedObject;
}

前面有看到過, SmartInstantiationAwareBeanPostProcessor 可以用來選擇構造函數, 那麼這裡, 他還可以用來暴露 bean 的早期引用. 

此例中, 就是暴露 IndexA 的早期引用. 此時 IndexA 還沒有進行初始化, 是一個半成品.

如果有對 IndexA 進行 AOP , 那麼也會在這裡進行一次代理. 將代理過的對象暴露給 IndexB.

 

還是通過調試的方式, 來確定下, 這邊有那些後置處理器能滿足條件:

1. ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor

2. AutowiredAnnotationBeanPostProcessor

 

ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor

由其父類實現:

org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter#getEarlyBeanReference

@Override
public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
    return bean;
}

ImportAwareBeanPostProcessor 在 創建 bean 的這整個過程中, 出現的頻率蠻高的, 但是大部分都是來湊熱鬧的.

 

AutowiredAnnotationBeanPostProcessor

也是由其父類實現:

org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter#getEarlyBeanReference

@Override
public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
    return bean;
}

從這裡可以看出, 正常情況下(不需要代理時), 該是什麼, 這裡就返回什麼, 不會對 bean 進行任何操作

 

 

上面說, 在這個後置處理器的處理裡面, 可能會產生代理, 為了印證這個問題, 需要對實例代碼進行一些小的修改:

@Component
@Aspect
public class Aopa {

    @Pointcut("execution(* com.study.ioc.cyc.IndexA.*(..))")
    public void pointCutMethodA() {
    }


    @Before("pointCutMethodA()")
    public void beforeA() {
        System.out.println("before invoke indexA.*() method -- Aopa");
    }
}


@EnableAspectJAutoProxy
@Configuration
@ComponentScan({
         "com.study.ioc.cyc"
        , "com.study.ioc.aop"
})
public class StartConfig {
}

此時, 再到方法裡面進行調試, 會發現多出來一個後置處理器, 變成了三個:

1. ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor

2. AnnotationAwareAspectJAutoProxyCreator

3. AutowiredAnnotationBeanPostProcessor

 

AnnotationAwareAspectJAutoProxyCreator

@Override
public Object getEarlyBeanReference(Object bean, String beanName) {
    Object cacheKey = getCacheKey(bean.getClass(), beanName);
    this.earlyProxyReferences.put(cacheKey, bean);
    return wrapIfNecessary(bean, beanName, cacheKey);
}

進 wrapIfNecessary 中看:

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
        return bean;
    }
    if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
        return bean;
    }
    if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
        this.advisedBeans.put(cacheKey, Boolean.FALSE);
        return bean;
    }

    // Create proxy if we have advice.
    Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    if (specificInterceptors != DO_NOT_PROXY) {
        this.advisedBeans.put(cacheKey, Boolean.TRUE);
        Object proxy = createProxy(
                bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
        this.proxyTypes.put(cacheKey, proxy.getClass());
        return proxy;
    }

    this.advisedBeans.put(cacheKey, Boolean.FALSE);
    return bean;
}

這裡看到, 有一個創建代理的方法. 確實是通過這裡, 產生了代理方法.

 

此例中, 如果aop裡面, 把 IndexB 也加進去, 那麼 IndexB 是不是也會在這裡進行代理呢?

答案是否定的. IndexB在此例中, 不會進這個方法的. 對於 IndexB 來說, 其實是一個正常的創建過程.

IndexB 的代理, 會在別的地方進行.(initializeBean中 - 初始化之後的後置處理器中完成代理) 

這個在後面就能看到

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在一些小的應用中,難免會用到資料庫,Sqlite資料庫以其小巧輕便,無需安裝,移植性好著稱,本文主要以一個簡單的小例子,簡述Python在Sqlite資料庫方面的應用,僅供學習分享使用,如有不足之處,還請指正。 ...
  • Optional Optional 類是一個可以為null的容器對象。可以很好的解決空指針異常。 1 創建Optional對象 創建一個空的Optional對象 Optional<String> empty = Optional.empty(); 創建一個非空的Optional對象 Optional ...
  • Apache Kafka 架構和相關概念 Apache Kafka 是一款開源的分散式消息引擎系統 消息引擎的同類 ActiveMQ RabbitMQ WebSphere MQ Rocket MQ JMS僅僅是一組 API 協議 消息引擎的作用 削峰填谷 緩衝上下游瞬時突發流量,使其更平滑.特別是對 ...
  • 百度雲盤:Python Cookbook(第3版)PDF高清完整版免費下載 提取碼:i2y5 豆瓣評分: 內容簡介 《Python Cookbook(第3版)中文版》介紹了Python應用在各個領域中的一些使用技巧和方法,其主題涵蓋了數據結構和演算法,字元串和文本,數字、日期和時間,迭代器和生成器,文 ...
  • JDK動態代理和 CGLIB 代理 JDK動態代理:其代理對象必須是某個介面的實現,它是通過在運行期期間創建一個介面的實現類來完成對目標對象的代理。 代碼示例 介面 public interface IUserDao { void save(); } 實現類 public class UserDao ...
  • spring在初始化之後, 還調用了一次 Bean 的後置處理器. 代碼片段: org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterIniti ...
  • 代碼片段: org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization @Override public Object ...
  • 當spring完成屬性註入之後, 就要開始 bean 的初始化了 代碼片段: org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean // Initialize the bea ...
一周排行
    -Advertisement-
    Play Games
  • 1. 說明 /* Performs operations on System.String instances that contain file or directory path information. These operations are performed in a cross-pla ...
  • 視頻地址:【WebApi+Vue3從0到1搭建《許可權管理系統》系列視頻:搭建JWT系統鑒權-嗶哩嗶哩】 https://b23.tv/R6cOcDO qq群:801913255 一、在appsettings.json中設置鑒權屬性 /*jwt鑒權*/ "JwtSetting": { "Issuer" ...
  • 引言 集成測試可在包含應用支持基礎結構(如資料庫、文件系統和網路)的級別上確保應用組件功能正常。 ASP.NET Core 通過將單元測試框架與測試 Web 主機和記憶體中測試伺服器結合使用來支持集成測試。 簡介 集成測試與單元測試相比,能夠在更廣泛的級別上評估應用的組件,確認多個組件一起工作以生成預 ...
  • 在.NET Emit編程中,我們探討了運算操作指令的重要性和應用。這些指令包括各種數學運算、位操作和比較操作,能夠在動態生成的代碼中實現對數據的處理和操作。通過這些指令,開發人員可以靈活地進行算術運算、邏輯運算和比較操作,從而實現各種複雜的演算法和邏輯......本篇之後,將進入第七部分:實戰項目 ...
  • 前言 多表頭表格是一個常見的業務需求,然而WPF中卻沒有預設實現這個功能,得益於WPF強大的控制項模板設計,我們可以通過修改控制項模板的方式自己實現它。 一、需求分析 下圖為一個典型的統計表格,統計1-12月的數據。 此時我們有一個需求,需要將月份按季度劃分,以便能夠直觀地看到季度統計數據,以下為該需求 ...
  • 如何將 ASP.NET Core MVC 項目的視圖分離到另一個項目 在當下這個年代 SPA 已是主流,人們早已忘記了 MVC 以及 Razor 的故事。但是在某些場景下 SSR 還是有意想不到效果。比如某些靜態頁面,比如追求首屏載入速度的時候。最近在項目中回歸傳統效果還是不錯。 有的時候我們希望將 ...
  • System.AggregateException: 發生一個或多個錯誤。 > Microsoft.WebTools.Shared.Exceptions.WebToolsException: 生成失敗。檢查輸出視窗瞭解更多詳細信息。 內部異常堆棧跟蹤的結尾 > (內部異常 #0) Microsoft ...
  • 引言 在上一章節我們實戰了在Asp.Net Core中的項目實戰,這一章節講解一下如何測試Asp.Net Core的中間件。 TestServer 還記得我們在集成測試中提供的TestServer嗎? TestServer 是由 Microsoft.AspNetCore.TestHost 包提供的。 ...
  • 在發現結果為真的WHEN子句時,CASE表達式的真假值判斷會終止,剩餘的WHEN子句會被忽略: CASE WHEN col_1 IN ('a', 'b') THEN '第一' WHEN col_1 IN ('a') THEN '第二' ELSE '其他' END 註意: 統一各分支返回的數據類型. ...
  • 在C#編程世界中,語法的精妙之處往往體現在那些看似微小卻極具影響力的符號與結構之中。其中,“_ =” 這一組合突然出現還真不知道什麼意思。本文將深入剖析“_ =” 的含義、工作原理及其在實際編程中的廣泛應用,揭示其作為C#語法奇兵的重要角色。 一、下劃線 _:神秘的棄元符號 下劃線 _ 在C#中並非 ...