Bean後置處理器 - InstantiationAwareBeanPostProcessor#postProcessProperties

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

代碼片段: org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean boolean hasInstAwareBpps = hasInstantiationAwareBeanPo ...


代碼片段:

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

boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
//深度引用檢查, 引用再引用
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
    if (pvs == null) {
        pvs = mbd.getPropertyValues();
    }
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
        if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            //這裡也是調用的實例化後的後置處理器, 只是調用的方法不一樣
       //這裡會進行 @Autowired 和 @Resource 的註入工作
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { return; } } pvs = pvsToUse; } } }

同樣的, 通過調試的方式, 來確定這裡使用了那些後置處理器:

1.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor

2.CommonAnnotationBeanPostProcessor

3.AutowiredAnnotationBeanPostProcessor

 

ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor

@Override
public PropertyValues postProcessProperties(@Nullable PropertyValues pvs, Object bean, String beanName) {
    // Inject the BeanFactory before AutowiredAnnotationBeanPostProcessor's
    // postProcessProperties method attempts to autowire other configuration beans.
    if (bean instanceof EnhancedConfiguration) {
        ((EnhancedConfiguration) bean).setBeanFactory(this.beanFactory);
    }
    return pvs;
}

這裡是對 EnhancedConfiguration 提供支持. 其實他繼承了 BeanFactoryAware 介面, 並且什麼都沒乾

public interface EnhancedConfiguration extends BeanFactoryAware {}

EnhancedConfiguration 是 ConfigurationClassEnhancer 的一個內部介面, 是給 spring 自己內部使用的, 開發人員用不了這個, 也沒必要

 

CommonAnnotationBeanPostProcessor

@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
    //找出類中標註了@Resource註解的屬性和方法
    //else if (field.isAnnotationPresent(Resource.class))
    InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);
    try {
        metadata.inject(bean, beanName, pvs);
    }
    catch (Throwable ex) {
        throw new BeanCreationException(beanName, "Injection of resource dependencies failed", ex);
    }
    return pvs;
}

這裡主要是對 @Resource 進行註入

findResourceMetadata在MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition的時候執行過.

所以這裡, 大概率是從緩存中拿取結果, 然後進行註入操作. 事實上, 也確實如此.

 

inject 最終會調用

org.springframework.beans.factory.annotation.InjectionMetadata.InjectedElement#inject 方法

protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
        throws Throwable {

    if (this.isField) {
        Field field = (Field) this.member;
        ReflectionUtils.makeAccessible(field);
        field.set(target, getResourceToInject(target, requestingBeanName));
    }
    else {
        if (checkPropertySkipping(pvs)) {
            return;
        }
        try {
            Method method = (Method) this.member;
            ReflectionUtils.makeAccessible(method);
            method.invoke(target, getResourceToInject(target, requestingBeanName));
        }
        catch (InvocationTargetException ex) {
            throw ex.getTargetException();
        }
    }
}

這裡分兩種情況進行處理, 一種是 通過欄位註入, 另一種是通過方法註入.

欄位註入的方式是比較多見的. 

getResourceToInject() 方法是一個被重寫了的方法:

org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.ResourceElement#getResourceToInject

他是在一個內部類中被重寫的方法.

@Override
protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) {
    return (this.lazyLookup ? buildLazyResourceProxy(this, requestingBeanName) :
            getResource(this, requestingBeanName));
}

預設情況下, lazy = false, 所以會走 getResource() 方法

org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#getResource

protected Object getResource(LookupElement element, @Nullable String requestingBeanName)
        throws NoSuchBeanDefinitionException {

    if (StringUtils.hasLength(element.mappedName)) {
        return this.jndiFactory.getBean(element.mappedName, element.lookupType);
    }
    if (this.alwaysUseJndiLookup) {
        return this.jndiFactory.getBean(element.name, element.lookupType);
    }
    if (this.resourceFactory == null) {
        throw new NoSuchBeanDefinitionException(element.lookupType,
                "No resource factory configured - specify the 'resourceFactory' property");
    }
    return autowireResource(this.resourceFactory, element, requestingBeanName);
}

根據設置的不同屬性, 進不同的方法, 這裡主要看 autowireResource , 因為一般情況是不需要去設置這些屬性的

protected Object autowireResource(BeanFactory factory, LookupElement element, @Nullable String requestingBeanName)
        throws NoSuchBeanDefinitionException {

    Object resource;
    Set<String> autowiredBeanNames;
    String name = element.name;

    if (factory instanceof AutowireCapableBeanFactory) {
        AutowireCapableBeanFactory beanFactory = (AutowireCapableBeanFactory) factory;
        DependencyDescriptor descriptor = element.getDependencyDescriptor();
        //優先使用 根據 name 註入, 這個 name 就是 beanName
        //當 beanName 找不到時, 才就會去根據 type 來註入
        //依據是 !factory.containsBean(name) 
        if (this.fallbackToDefaultTypeMatch && element.isDefaultName && !factory.containsBean(name)) {
            autowiredBeanNames = new LinkedHashSet<>();
            //根據type(類型)來進行依賴註入
            resource = beanFactory.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, null);
            if (resource == null) {
                //如果返回時 resource , 則表明, spring容器中找不到, 也創建不了 這個依賴的bean
                throw new NoSuchBeanDefinitionException(element.getLookupType(), "No resolvable resource object");
            }
        }
        else {
            //根據name(名稱)來進行依賴註入
            resource = beanFactory.resolveBeanByName(name, descriptor);
            autowiredBeanNames = Collections.singleton(name);
        }
    }
    else {
        resource = factory.getBean(name, element.lookupType);
        autowiredBeanNames = Collections.singleton(name);
    }

    if (factory instanceof ConfigurableBeanFactory) {
        ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory) factory;
        for (String autowiredBeanName : autowiredBeanNames) {
            if (requestingBeanName != null && beanFactory.containsBean(autowiredBeanName)) {
                beanFactory.registerDependentBean(autowiredBeanName, requestingBeanName);
            }
        }
    }

    return resource;
}

都說, @Resource 在不設置 name 和 type 的情況下, 是優先使用 name 去 獲取/創建 依賴的 bean , 如果name找不到, 才會使用 type.

這段代碼, 就是支撐的依據.

 

AutowiredAnnotationBeanPostProcessor

@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
    InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
    try {
        metadata.inject(bean, beanName, pvs);
    }
    catch (BeanCreationException ex) {
        throw ex;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
    }
    return pvs;
}

這裡主要是對 @Autowired 和 @Value 進行註入的. findAutowiringMetadata

findAutowiringMetadata在MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition的時候執行過.

所以此處, 是從緩存中拿取結果, 然後進行註入操作.

最終會調用本類中的方法:

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject

@Override
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
    Field field = (Field) this.member;
    Object value;
    if (this.cached) {
        value = resolvedCachedArgument(beanName, this.cachedFieldValue);
    }
    else {
        DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
        desc.setContainingClass(bean.getClass());
        Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
        Assert.state(beanFactory != null, "No BeanFactory available");
        TypeConverter typeConverter = beanFactory.getTypeConverter();
        try {
            //根據 type 進行依賴註入
            value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
        }
        catch (BeansException ex) {
            throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
        }
        synchronized (this) {
            if (!this.cached) {
                if (value != null || this.required) {
                    this.cachedFieldValue = desc;
                    registerDependentBeans(beanName, autowiredBeanNames);
                    if (autowiredBeanNames.size() == 1) {
                        String autowiredBeanName = autowiredBeanNames.iterator().next();
                        if (beanFactory.containsBean(autowiredBeanName) &&
                                beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
                            this.cachedFieldValue = new ShortcutDependencyDescriptor(
                                    desc, autowiredBeanName, field.getType());
                        }
                    }
                }
                else {
                    this.cachedFieldValue = null;
                }
                this.cached = true;
            }
        }
    }
    if (value != null) {
        ReflectionUtils.makeAccessible(field);
        field.set(bean, value);
    }
}

 

這裡有一個隱藏的後置處理器: SmartInstantiationAwareBeanPostProcessor

留到下一篇看


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

-Advertisement-
Play Games
更多相關文章
  • 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 ...
  • 示例 @Component public class IndexA { @Autowired IndexB bbb; public IndexA() { System.out.println("IndexA constructor..."); } public void printf(){ Syst ...
一周排行
    -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#中並非 ...