doCreateBean - createBeanInstance

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

接著前面, 看完構造函數前的後置處理器, 就到 doCreateBean 方法了. protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] ...


接著前面, 看完構造函數前的後置處理器, 就到 doCreateBean 方法了.

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
            throws BeanCreationException {

    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        /**
         * 創建 bean 實例,並將實例包裹在 BeanWrapper 實現類對象中返回。
         * createBeanInstance中包含三種創建 bean 實例的方式:
         *   1. 通過工廠方法創建 bean 實例
         *   2. 通過構造方法自動註入(autowire by constructor)的方式創建 bean 實例
         *   3. 通過無參構造方法方法創建 bean 實例
         *
         * 若 bean 的配置信息中配置了 lookup-method 和 replace-method,則會使用 CGLIB 增強 bean 實例。
         */
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    final Object bean = instanceWrapper.getWrappedInstance();
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
        mbd.resolvedTargetType = beanType;
    }

    // Allow post-processors to modify the merged bean definition.
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                //調用屬性合併後置處理器, 進行屬性合併
                //這裡會進行 一些註解 的掃描
                //CommonAnnotationBeanPostProcessor -> @PostConstruct @PreDestroy @Resource
                //AutowiredAnnotationBeanPostProcessor -> @Autowired @Value
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }

    // Eagerly cache singletons to be able to resolve circular references
    // even when triggered by lifecycle interfaces like BeanFactoryAware.
    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));
    }

    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
        //設置屬性,非常重要
        populateBean(beanName, mbd, instanceWrapper);
        //執行後置處理器,aop就是在這裡完成的處理
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
    catch (Throwable ex) {
        if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
            throw (BeanCreationException) ex;
        }
        else {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
        }
    }

    if (earlySingletonExposure) {
        Object earlySingletonReference = getSingleton(beanName, false);
        if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
            }
            else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                String[] dependentBeans = getDependentBeans(beanName);
                Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                    if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                        actualDependentBeans.add(dependentBean);
                    }
                }
                if (!actualDependentBeans.isEmpty()) {
                    throw new BeanCurrentlyInCreationException(beanName,
                            "Bean with name '" + beanName + "' has been injected into other beans [" +
                            StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                            "] in its raw version as part of a circular reference, but has eventually been " +
                            "wrapped. This means that said other beans do not use the final version of the " +
                            "bean. This is often the result of over-eager type matching - consider using " +
                            "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
                }
            }
        }
    }

    // Register bean as disposable.
    try {
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }

    return exposedObject;
}

1. 第一次進來時, 對象肯定是null, 所以會進行一次反射創建過程.

2. 然後會執行屬性合併後置處理器, 在這個後置處理器中, 會進行一些屬性合併和一些註解的掃描

3. 合併完屬性之後, 就要進行屬性的註入了, 比如 @Autowired 註入

4. 開始初始化過程, 調用 一些初始化方法

 

整個過程是非常符合邏輯的.

沒有對象則創建對象, 有了對象之後, 看看有那些屬性需要註入, 當屬性都準備妥當時, 執行初始化方法, 比如對這些屬性做一些什麼操作或者通過這些屬性, 拿到一些什麼東西等等.

 

createBeanInstance

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

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
    // Make sure bean class is actually resolved at this point.
    Class<?> beanClass = resolveBeanClass(mbd, beanName);

    //檢測一個類的訪問許可權, spring預設情況下對於非public的類是允許訪問的。
    if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
    }

    Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
    if (instanceSupplier != null) {
        return obtainFromSupplier(instanceSupplier, beanName);
    }


    // 如果工廠方法不為空,則通過工廠方法構建 bean 對象
    // 這種是在 xml 中配置 bean 的 factory-method
    if (mbd.getFactoryMethodName() != null) {
        return instantiateUsingFactoryMethod(beanName, mbd, args);
    }

    // Shortcut when re-creating the same bean...
    /**
     * 從spring的原始註釋可以知道這個是一個Shortcut,什麼意思呢?
     * 當多次構建同一個 bean 時,可以使用這個Shortcut,
     * 也就是說不在需要次推斷應該使用哪種方式構造bean
     *  比如在多次構建同一個prototype類型的 bean 時,就可以走此處的shortcut
     * 這裡的 resolved 和 mbd.constructorArgumentsResolved 將會在 bean 第一次實例
     * 化的過程中被設置
     */
    boolean resolved = false;
    //自動裝配
    boolean autowireNecessary = false;
    if (args == null) {
        synchronized (mbd.constructorArgumentLock) {
            if (mbd.resolvedConstructorOrFactoryMethod != null) {
                resolved = true;
                //如果已經解析了構造方法的參數,則必須要通過一個帶參構造方法來實例
                autowireNecessary = mbd.constructorArgumentsResolved;
            }
        }
    }
    if (resolved) {
        if (autowireNecessary) {
            // 通過構造方法自動裝配的方式構造 bean 對象
            return autowireConstructor(beanName, mbd, null, null);
        }
        else {
            //通過預設的無參構造方法進行
            return instantiateBean(beanName, mbd);
        }
    }

    // Candidate constructors for autowiring?
    // 由後置處理器決定返回哪些構造方法, 當出現多個構造函數時, 返回為 null
    // 這裡的後置處理器是 SmartInstantiationAwareBeanPostProcessor, 調用其 determineCandidateConstructors 方法
    // 具體處理在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor 中進行
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
            mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
        //需要對構造函數的參數進行註入, 可以通過 ImportBeanDefinitionRegistrar 來修改 bd 的自動裝配模式:
        // AnnotatedGenericBeanDefinition bd = new AnnotatedGenericBeanDefinition(IndexDao1.class);
        // bd.setAutowireMode(AnnotatedGenericBeanDefinition.AUTOWIRE_CONSTRUCTOR);
        // registry.registerBeanDefinition("indexDao1", bd);
        return autowireConstructor(beanName, mbd, ctors, args);
    }

    // Preferred constructors for default construction?
    ctors = mbd.getPreferredConstructors();
    if (ctors != null) {
        return autowireConstructor(beanName, mbd, ctors, null);
    }

    // No special handling: simply use no-arg constructor.
    //使用預設的無參構造方法進行初始化
    return instantiateBean(beanName, mbd);
}

我通常的使用習慣是, 使用 @Autowired 來進行註入操作(雖然有些人提倡通過構造註入的方式). 

按照我這個習慣, 構造函數是預設構造函數, actors 返回來是null , 所以不會走 autowireConstructor 來創建,

而是會走到 最下麵, 在 instantiateBean() 中, 通過無參構造函數反射創建對象. 

這種創建對象的方式, 是最簡單的. 同時能避免一個 構造函數造成的相互依賴問題, 這個問題是無解的.

 

determineConstructorsFromBeanPostProcessors

這裡會調用構造函數的後置處理器, 來進行構造函數的選擇

@Nullable
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
        throws BeansException {

    if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
                if (ctors != null) {
                    return ctors;
                }
            }
        }
    }
    return null;
}

這個後置處理器, 只能放在下一篇來看了, 這裡先不管了. 其中的道道, 還是蠻多的.

 

instantiateBean

protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
    try {
        Object beanInstance;
        final BeanFactory parent = this;
        if (System.getSecurityManager() != null) {
            beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
                    getInstantiationStrategy().instantiate(mbd, beanName, parent),
                    getAccessControlContext());
        }
        else {
            //getInstantiationStrategy()得到類的實例化策略
            //得到一個反射的實例化策略 : SimpleInstantiationStrategy
            beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
        }
        BeanWrapper bw = new BeanWrapperImpl(beanInstance);
        initBeanWrapper(bw);
        return bw;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
}

這裡就是實例化 bean 的地方了, 

實例化之後, 還會設置一些屬性轉換器

 

SimpleInstantiationStrategy.instantiate

@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
    // Don't override the class with CGLIB if no overrides.
    //檢測 bean 配置中是否配置了 lookup-method 或 replace-method
    //如果配置了就需使用 CGLIB 構建 bean 對象
    if (!bd.hasMethodOverrides()) {
        Constructor<?> constructorToUse;
        synchronized (bd.constructorArgumentLock) {
            constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
            if (constructorToUse == null) {
                final Class<?> clazz = bd.getBeanClass();
                if (clazz.isInterface()) {
                    throw new BeanInstantiationException(clazz, "Specified class is an interface");
                }
                try {
                    if (System.getSecurityManager() != null) {
                        constructorToUse = AccessController.doPrivileged(
                                (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
                    }
                    else {
                        constructorToUse = clazz.getDeclaredConstructor();
                    }
                    bd.resolvedConstructorOrFactoryMethod = constructorToUse;
                }
                catch (Throwable ex) {
                    throw new BeanInstantiationException(clazz, "No default constructor found", ex);
                }
            }
        }
        return BeanUtils.instantiateClass(constructorToUse);
    }
    else {
        // Must generate CGLIB subclass.
        return instantiateWithMethodInjection(bd, beanName, owner);
    }
}

BeanUtils.instantiateClass 就是反射創建對象的方法.

這裡雖說有創建 cglib 的方法, 但是裡面只是拋出了異常

throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");

lookup-method 和 replace-method , 我基本都只是在學習的時候, 才去使用過, 如果想要用的話, 需要改變這裡的實例化策略, 也就是不用 SimpleInstantiationStrategy .

 

initBeanWrapper

org.springframework.beans.factory.support.AbstractBeanFactory#initBeanWrapper

protected void initBeanWrapper(BeanWrapper bw) {
    bw.setConversionService(getConversionService());
    registerCustomEditors(bw);
}

ConversionService 是做屬性轉換的

registerCustomEditors 其實就是註冊一些屬性轉換器. 如:

org.springframework.beans.support.ResourceEditorRegistrar#registerCustomEditors

@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
    ResourceEditor baseEditor = new ResourceEditor(this.resourceLoader, this.propertyResolver);
    doRegisterEditor(registry, Resource.class, baseEditor);
    doRegisterEditor(registry, ContextResource.class, baseEditor);
    doRegisterEditor(registry, InputStream.class, new InputStreamEditor(baseEditor));
    doRegisterEditor(registry, InputSource.class, new InputSourceEditor(baseEditor));
    doRegisterEditor(registry, File.class, new FileEditor(baseEditor));
    doRegisterEditor(registry, Path.class, new PathEditor(baseEditor));
    doRegisterEditor(registry, Reader.class, new ReaderEditor(baseEditor));
    doRegisterEditor(registry, URL.class, new URLEditor(baseEditor));

    ClassLoader classLoader = this.resourceLoader.getClassLoader();
    doRegisterEditor(registry, URI.class, new URIEditor(classLoader));
    doRegisterEditor(registry, Class.class, new ClassEditor(classLoader));
    doRegisterEditor(registry, Class[].class, new ClassArrayEditor(classLoader));

    if (this.resourceLoader instanceof ResourcePatternResolver) {
        doRegisterEditor(registry, Resource[].class,
                new ResourceArrayPropertyEditor((ResourcePatternResolver) this.resourceLoader, this.propertyResolver));
    }
}

 

autowireConstructor

想進這個方法, 其實也簡單. 方法有很多種, 其中一種最簡單的, 就是只放一個有參構造方法就行了.

在這裡, spring會根據自己的規則, 來進行 構造函數的選擇. 其選擇有限級為:

1. 優先按照訪問許可權, public 放在前面

2. 然後按照參數個數, 參數多的放在前面.

1. public IndexDao(Object o1, Object o2, Object o3)
2. public IndexDao(Object o1, Object o2)
3. public IndexDao(Object o1)
4. protected IndexDao(Integer i, Object o1, Object o2, Object o3)
5. protected IndexDao(Integer i, Object o1, Object o2)
6. protected IndexDao(Integer i, Object o1)

具體邏輯就不看了, 大致是這麼個效果.

當選擇好後, 就回進行創建工作. 當碰到構造參數時, 會去從容器中 獲取/創建 對象

 


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

-Advertisement-
Play Games
更多相關文章
一周排行
    -Advertisement-
    Play Games
  • 前言 在我們開發過程中基本上不可或缺的用到一些敏感機密數據,比如SQL伺服器的連接串或者是OAuth2的Secret等,這些敏感數據在代碼中是不太安全的,我們不應該在源代碼中存儲密碼和其他的敏感數據,一種推薦的方式是通過Asp.Net Core的機密管理器。 機密管理器 在 ASP.NET Core ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 順序棧的介面程式 目錄順序棧的介面程式頭文件創建順序棧入棧出棧利用棧將10進位轉16進位數驗證 頭文件 #include <stdio.h> #include <stdbool.h> #include <stdlib.h> 創建順序棧 // 指的是順序棧中的元素的數據類型,用戶可以根據需要進行修改 ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • C總結與剖析:關鍵字篇 -- <<C語言深度解剖>> 目錄C總結與剖析:關鍵字篇 -- <<C語言深度解剖>>程式的本質:二進位文件變數1.變數:記憶體上的某個位置開闢的空間2.變數的初始化3.為什麼要有變數4.局部變數與全局變數5.變數的大小由類型決定6.任何一個變數,記憶體賦值都是從低地址開始往高地 ...
  • 如果讓你來做一個有狀態流式應用的故障恢復,你會如何來做呢? 單機和多機會遇到什麼不同的問題? Flink Checkpoint 是做什麼用的?原理是什麼? ...
  • C++ 多級繼承 多級繼承是一種面向對象編程(OOP)特性,允許一個類從多個基類繼承屬性和方法。它使代碼更易於組織和維護,並促進代碼重用。 多級繼承的語法 在 C++ 中,使用 : 符號來指定繼承關係。多級繼承的語法如下: class DerivedClass : public BaseClass1 ...
  • 前言 什麼是SpringCloud? Spring Cloud 是一系列框架的有序集合,它利用 Spring Boot 的開發便利性簡化了分散式系統的開發,比如服務註冊、服務發現、網關、路由、鏈路追蹤等。Spring Cloud 並不是重覆造輪子,而是將市面上開發得比較好的模塊集成進去,進行封裝,從 ...
  • class_template 類模板和函數模板的定義和使用類似,我們已經進行了介紹。有時,有兩個或多個類,其功能是相同的,僅僅是數據類型不同。類模板用於實現類所需數據的類型參數化 template<class NameType, class AgeType> class Person { publi ...
  • 目錄system v IPC簡介共用記憶體需要用到的函數介面shmget函數--獲取對象IDshmat函數--獲得映射空間shmctl函數--釋放資源共用記憶體實現思路註意 system v IPC簡介 消息隊列、共用記憶體和信號量統稱為system v IPC(進程間通信機制),V是羅馬數字5,是UNI ...