Bean後置處理器 - BeanPostProcessor#postProcessAfterInitialization

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

spring在初始化之後, 還調用了一次 Bean 的後置處理器. 代碼片段: org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterIniti ...


spring在初始化之後, 還調用了一次 Bean 的後置處理器.

代碼片段:

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

@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
        throws BeansException {

    Object result = existingBean;
    for (BeanPostProcessor processor : getBeanPostProcessors()) {
        Object current = processor.postProcessAfterInitialization(result, beanName);
        if (current == null) {
            return result;
        }
        result = current;
    }
    return result;
}

 同樣的, 這裡肯定也是6個後置處理器.

 

1.ApplicationContextAwareProcessor

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
    return bean;
}

這裡啥也沒乾

 

2.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor

由父類實現:

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

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

 

3.PostProcessorRegistrationDelegate$BeanPostProcessorChecker

org.springframework.context.support.PostProcessorRegistrationDelegate.BeanPostProcessorChecker#postProcessAfterInitialization

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
    if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) &&
            this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
        if (logger.isInfoEnabled()) {
            logger.info("Bean '" + beanName + "' of type [" + bean.getClass().getName() +
                    "] is not eligible for getting processed by all BeanPostProcessors " +
                    "(for example: not eligible for auto-proxying)");
        }
    }
    return bean;
}

private boolean isInfrastructureBean(@Nullable String beanName) {
    if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) {
        BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName);
        return (bd.getRole() == RootBeanDefinition.ROLE_INFRASTRUCTURE);
    }
    return false;
}

從這裡看, 並沒有做實質性的操作, 主要是記錄了日誌.

主要是一個驗證, 看看 執行過的後置處理器數量和目標數量, 是否相同.

其關鍵代碼:

org.springframework.context.support.PostProcessorRegistrationDelegate#registerBeanPostProcessors

int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

 

4.CommonAnnotationBeanPostProcessor

由其父類實現:

org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor#postProcessAfterInitialization

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

裡面啥也沒乾

 

5.AutowiredAnnotationBeanPostProcessor

由其父類實現:

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

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

 

6.ApplicationListenerDetector

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
    if (bean instanceof ApplicationListener) {
        // potentially not detected as a listener by getBeanNamesForType retrieval
        Boolean flag = this.singletonNames.get(beanName);
        if (Boolean.TRUE.equals(flag)) {
            // singleton bean (top-level or inner): register on the fly
            this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
        }
        else if (Boolean.FALSE.equals(flag)) {
            if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
                // inner bean with other scope - can't reliably process events
                logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
                        "but is not reachable for event multicasting by its containing ApplicationContext " +
                        "because it does not have singleton scope. Only top-level listener beans are allowed " +
                        "to be of non-singleton scope.");
            }
            this.singletonNames.remove(beanName);
        }
    }
    return bean;
}

這裡主要是將 實現了 ApplicationListener 介面的監聽器, 加入到容器中.

如:

@Component
public class MyListener implements ApplicationListener<ApplicationEvent> {
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("MyListener : " + event);
    }
}

 

都說在這一步能產生 aop 代理, 那麼從上面的代碼, 暫時還沒有看到. 接著前面的例子 getEarlyBeanReference 來看

示例

@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()));
    }
}

@Component
@Aspect
public class Aopa {

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

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

    @Pointcut("execution(* com.study.elvinle.ioc.cyc.IndexB.*(..))")
    public void pointCutMethodB() {
    }

    @Before("pointCutMethodB()")
    public void beforeB() {
        System.out.println("before invoke indexB.*() method -- Aopa");
    }
}

@EnableAspectJAutoProxy
@Configuration
@ComponentScan({
         "com.study.elvinle.ioc.cyc"
        , "com.study.elvinle.ioc.aop"
})
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();
}

調試結果:

 

 通過調試 applyBeanPostProcessorsAfterInitialization 方法看到, 此處多了一個後置處理器: 

AnnotationAwareAspectJAutoProxyCreator

 

AnnotationAwareAspectJAutoProxyCreator

方法藏的比較深, 由父類實現:

org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization

@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
    if (bean != null) {
        Object cacheKey = getCacheKey(bean.getClass(), beanName);
        if (this.earlyProxyReferences.remove(cacheKey) != bean) {
            return wrapIfNecessary(bean, beanName, cacheKey);
        }
    }
    return bean;
}

可以看到, 這裡調用了前面同樣的方法, 來產生代理:

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 代理的產生, 並不是全在 初始化方法之後的後置處理器中產生的. 

還有一部分是在 SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference 中產生的.

IndexA 在 getEarlyBeanReference 中產生代理之後, 在這裡會再產生一次嗎? 

答案是否定的. spring 很強大, 不會犯這種低級錯誤.

 


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

-Advertisement-
Play Games
更多相關文章
  • 代理模式的目地是為對象提供一種代理以控制對這個對象的訪問。為什麼會出現“通過一個代理對象,控制其他對象訪問目標對象”這種場景,而不知直接new()出一個對象直接使用呢?這是因為在有些場景下對象的訪問比較複雜,且需要一些額外的控制,這時如果直接new()出實例,併在調用端處理這些繁雜的細節,會增加系統 ...
  • 簡介 在企業級開發中、我們經常會有編寫資料庫表結構文檔的時間付出,從業以來,待過幾家企業,關於資料庫表結構文檔狀態:要麼沒有、要麼有、但都是手寫、後期運維開發,需要手動進行維護到文檔中,很是繁瑣、如果忘記一次維護、就會給以後工作造成很多困擾、無形中製造了很多坑留給自己和後人,於是需要一個插件工具 s ...
  • K-Bag定義為K的多個任意全排列的組合(eg:1 2 3 2 3 1 1 2 3),給定一個長為n的數組,判斷是否為K-Bag的一部分。 題解: (1≤n≤5⋅105,1≤k≤109),k<=n時,用g[i]判斷前i個數是否不相等,h[i]判斷i~n是否不相等,f[i]判斷i~i+k是否不相等,b ...
  • 在一些小的應用中,難免會用到資料庫,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 ...
一周排行
    -Advertisement-
    Play Games
  • 1、預覽地址:http://139.155.137.144:9012 2、qq群:801913255 一、前言 隨著網路的發展,企業對於信息系統數據的保密工作愈發重視,不同身份、角色對於數據的訪問許可權都應該大相徑庭。 列如 1、不同登錄人員對一個數據列表的可見度是不一樣的,如數據列、數據行、數據按鈕 ...
  • 前言 上一篇文章寫瞭如何使用RabbitMQ做個簡單的發送郵件項目,然後評論也是比較多,也是準備去學習一下如何確保RabbitMQ的消息可靠性,但是由於時間原因,先來說說設計模式中的簡單工廠模式吧! 在瞭解簡單工廠模式之前,我們要知道C#是一款面向對象的高級程式語言。它有3大特性,封裝、繼承、多態。 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 介紹 Nodify是一個WPF基於節點的編輯器控制項,其中包含一系列節點、連接和連接器組件,旨在簡化構建基於節點的工具的過程 ...
  • 創建一個webapi項目做測試使用。 創建新控制器,搭建一個基礎框架,包括獲取當天日期、wiki的請求地址等 創建一個Http請求幫助類以及方法,用於獲取指定URL的信息 使用http請求訪問指定url,先運行一下,看看返回的內容。內容如圖右邊所示,實際上是一個Json數據。我們主要解析 大事記 部 ...
  • 最近在不少自媒體上看到有關.NET與C#的資訊與評價,感覺大家對.NET與C#還是不太瞭解,尤其是對2016年6月發佈的跨平臺.NET Core 1.0,更是知之甚少。在考慮一番之後,還是決定寫點東西總結一下,也回顧一下.NET的發展歷史。 首先,你沒看錯,.NET是跨平臺的,可以在Windows、 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 添加節點(nodes) 通過上一篇我們已經創建好了編輯器實例現在我們為編輯器添加一個節點 添加model和viewmode ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...
  • 類型檢查和轉換:當你需要檢查對象是否為特定類型,並且希望在同一時間內將其轉換為那個類型時,模式匹配提供了一種更簡潔的方式來完成這一任務,避免了使用傳統的as和is操作符後還需要進行額外的null檢查。 複雜條件邏輯:在處理複雜的條件邏輯時,特別是涉及到多個條件和類型的情況下,使用模式匹配可以使代碼更 ...
  • 在日常開發中,我們經常需要和文件打交道,特別是桌面開發,有時候就會需要載入大批量的文件,而且可能還會存在部分文件缺失的情況,那麼如何才能快速的判斷文件是否存在呢?如果處理不當的,且文件數量比較多的時候,可能會造成卡頓等情況,進而影響程式的使用體驗。今天就以一個簡單的小例子,簡述兩種不同的判斷文件是否... ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...