天天看點

Spring源碼分析之依賴注入

1、 依賴注入發生的時間

當 Spring IOC 容器完成了 Bean 定義資源的定位、 載入和解析注冊以後, IOC 容器中已經管理類 Bean

定義的相關資料, 但是此時 IOC 容器還沒有對所管理的 Bean 進行依賴注入, 依賴注入在以下兩種情況

發生:

(1).使用者第一次通過 getBean 方法向 IOC 容索要 Bean 時, IOC 容器觸發依賴注入。

(2).當使用者在 Bean 定義資源中為元素配置了 lazy-init 屬性,即讓容器在解析注冊 Bean 定義

時進行預執行個體化, 觸發依賴注入。

BeanFactory 接口定義了 Spring IOC 容器的基本功能規範, 是 Spring IOC 容器所應遵守的最底層和

最基本的程式設計規範。 BeanFactory 接口中定義了幾個 getBean 方法, 就是使用者向 IOC 容器索取管理的

Bean 的方法, 我們通過分析其子類的具體實作, 了解 Spring IOC 容器在使用者索取 Bean 時如何完成依

賴注入。

Spring源碼分析之依賴注入

在 BeanFactory 中我們看到 getBean(String…) 函數, 它的具體實作在 AbstractBeanFactory

中。

2、 AbstractBeanFactory 通過 getBean 向 IOC 容器擷取被管理的 Bean,

AbstractBeanFactory 的 getBean 相關方法的源碼如下:

@Override
    public Object getBean(String name) throws BeansException {
        assertBeanFactoryActive();
        return getBeanFactory().getBean(name);
    }

    //擷取IOC容器中指定名稱的Bean
    @Override
    public Object getBean(String name) throws BeansException {
        //doGetBean才是真正向IoC容器擷取被管理Bean的過程
        return doGetBean(name, null, null, false);
    }

    @SuppressWarnings("unchecked")
    //真正實作向IOC容器擷取Bean的功能,也是觸發依賴注入功能的地方
    protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
            @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

        //根據指定的名稱擷取被管理Bean的名稱,剝離指定名稱中對容器的相關依賴
        //如果指定的是别名,将别名轉換為規範的Bean名稱
        final String beanName = transformedBeanName(name);
        Object bean;

        // Eagerly check singleton cache for manually registered singletons.
        //先從緩存中取是否已經有被建立過的單态類型的Bean
        //對于單例模式的Bean整個IOC容器中隻建立一次,不需要重複建立
        Object sharedInstance = getSingleton(beanName);
        //IOC容器建立單例模式Bean執行個體對象
        if (sharedInstance != null && args == null) {
            if (logger.isDebugEnabled()) {
                //如果指定名稱的Bean在容器中已有單例模式的Bean被建立
                //直接傳回已經建立的Bean
                if (isSingletonCurrentlyInCreation(beanName)) {
                    logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
                            "' that is not fully initialized yet - a consequence of a circular reference");
                }
                else {
                    logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
                }
            }
            //擷取給定Bean的執行個體對象,主要是完成FactoryBean的相關處理
            //注意:BeanFactory是管理容器中Bean的工廠,而FactoryBean是
            //建立建立對象的工廠Bean,兩者之間有差別
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }

        else {
            // Fail if we're already creating this bean instance:
            // We're assumably within a circular reference.
            //緩存沒有正在建立的單例模式Bean
            //緩存中已經有已經建立的原型模式Bean
            //但是由于循環引用的問題導緻執行個體化對象失敗
            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }

            // Check if bean definition exists in this factory.
            //對IOC容器中是否存在指定名稱的BeanDefinition進行檢查,首先檢查是否
            //能在目前的BeanFactory中擷取的所需要的Bean,如果不能則委托目前容器
            //的父級容器去查找,如果還是找不到則沿着容器的繼承體系向父級容器查找
            BeanFactory parentBeanFactory = getParentBeanFactory();
            //目前容器的父級容器存在,且目前容器中不存在指定名稱的Bean
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                // Not found -> check parent.
                //解析指定Bean名稱的原始名稱
                String nameToLookup = originalBeanName(name);
                if (parentBeanFactory instanceof AbstractBeanFactory) {
                    return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                            nameToLookup, requiredType, args, typeCheckOnly);
                }
                else if (args != null) {
                    // Delegation to parent with explicit args.
                    //委派父級容器根據指定名稱和顯式的參數查找
                    return (T) parentBeanFactory.getBean(nameToLookup, args);
                }
                else {
                    // No args -> delegate to standard getBean method.
                    //委派父級容器根據指定名稱和類型查找
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
            }

            //建立的Bean是否需要進行類型驗證,一般不需要
            if (!typeCheckOnly) {
                //向容器标記指定的Bean已經被建立
                markBeanAsCreated(beanName);
            }

            try {
                //根據指定Bean名稱擷取其父級的Bean定義
                //主要解決Bean繼承時子類合并父類公共屬性問題
                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);

                // Guarantee initialization of beans that the current bean depends on.
                //擷取目前Bean所有依賴Bean的名稱
                String[] dependsOn = mbd.getDependsOn();
                //如果目前Bean有依賴Bean
                if (dependsOn != null) {
                    for (String dep : dependsOn) {
                        if (isDependent(beanName, dep)) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                        }
                        //遞歸調用getBean方法,擷取目前Bean的依賴Bean
                        registerDependentBean(dep, beanName);
                        //把被依賴Bean注冊給目前依賴的Bean
                        getBean(dep);
                    }
                }

                // Create bean instance.
                //建立單例模式Bean的執行個體對象
                if (mbd.isSingleton()) {
                    //這裡使用了一個匿名内部類,建立Bean執行個體對象,并且注冊給所依賴的對象
                    sharedInstance = getSingleton(beanName, () -> {
                        try {
                            //建立一個指定Bean執行個體對象,如果有父級繼承,則合并子類和父類的定義
                            return createBean(beanName, mbd, args);
                        }
                        catch (BeansException ex) {
                            // Explicitly remove instance from singleton cache: It might have been put there
                            // eagerly by the creation process, to allow for circular reference resolution.
                            // Also remove any beans that received a temporary reference to the bean.
                            //顯式地從容器單例模式Bean緩存中清除執行個體對象
                            destroySingleton(beanName);
                            throw ex;
                        }
                    });
                    //擷取給定Bean的執行個體對象
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }

                //IOC容器建立原型模式Bean執行個體對象
                else if (mbd.isPrototype()) {
                    // It's a prototype -> create a new instance.
                    //原型模式(Prototype)是每次都會建立一個新的對象
                    Object prototypeInstance = null;
                    try {
                        //回調beforePrototypeCreation方法,預設的功能是注冊目前建立的原型對象
                        beforePrototypeCreation(beanName);
                        //建立指定Bean對象執行個體
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {
                        //回調afterPrototypeCreation方法,預設的功能告訴IOC容器指定Bean的原型對象不再建立
                        afterPrototypeCreation(beanName);
                    }
                    //擷取給定Bean的執行個體對象
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }

                //要建立的Bean既不是單例模式,也不是原型模式,則根據Bean定義資源中
                //配置的生命周期範圍,選擇執行個體化Bean的合适方法,這種在Web應用程式中
                //比較常用,如:request、session、application等生命周期
                else {
                    String scopeName = mbd.getScope();
                    final Scope scope = this.scopes.get(scopeName);
                    //Bean定義資源中沒有配置生命周期範圍,則Bean定義不合法
                    if (scope == null) {
                        throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                    }
                    try {
                        //這裡又使用了一個匿名内部類,擷取一個指定生命周期範圍的執行個體
                        Object scopedInstance = scope.get(beanName, () -> {
                            beforePrototypeCreation(beanName);
                            try {
                                return createBean(beanName, mbd, args);
                            }
                            finally {
                                afterPrototypeCreation(beanName);
                            }
                        });
                        //擷取給定Bean的執行個體對象
                        bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                    }
                    catch (IllegalStateException ex) {
                        throw new BeanCreationException(beanName,
                                "Scope '" + scopeName + "' is not active for the current thread; consider " +
                                "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                                ex);
                    }
                }
            }
            catch (BeansException ex) {
                cleanupAfterBeanCreationFailure(beanName);
                throw ex;
            }
        }

        // Check if required type matches the type of the actual bean instance.
        //對建立的Bean執行個體對象進行類型檢查
        if (requiredType != null && !requiredType.isInstance(bean)) {
            try {
                T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
                if (convertedBean == null) {
                    throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
                }
                return convertedBean;
            }
            catch (TypeMismatchException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Failed to convert bean '" + name + "' to required type '" +
                            ClassUtils.getQualifiedName(requiredType) + "'", ex);
                }
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            }
        }
        return (T) bean;
    }   
           

通過上面對向 IOC 容器擷取 Bean 方法的分析, 我們可以看到在 Spring 中, 如果 Bean 定義的單例模式

(Singleton), 則容器在建立之前先從緩存中查找, 以確定整個容器中隻存在一個執行個體對象。 如果 Bean定義的是原型模式(Prototype), 則容器每次都會建立一個新的執行個體對象。 除此之外, Bean 定義還可

以擴充為指定其生命周期範圍。

上面的源碼隻是定義了根據 Bean 定義的模式, 采取的不同建立 Bean 執行個體對象的政策, 具體的 Bean 實

例 對 象 的 創 建 過 程 由 實 現 了 ObejctFactory 接 口 的 匿 名 内 部 類 的 createBean 方 法 完 成 ,

ObejctFactory 使 用 委 派 模 式 , 具 體 的 Bean 實 例 創 建 過 程 交 由 其 實 現 類

AbstractAutowireCapableBeanFactory 完 成 , 我 們 繼 續 分 析

AbstractAutowireCapableBeanFactory 的 createBean 方法的源碼, 了解其建立 Bean 執行個體的具體

實作過程。

3、 AbstractAutowireCapableBeanFactory 建立 Bean 執行個體對象:

AbstractAutowireCapableBeanFactory 類實作了 ObejctFactory 接口, 建立容器指定的 Bean 執行個體

對象, 同時還對建立的 Bean 執行個體對象進行初始化處理。 其建立 Bean 執行個體對象的方法源碼如下:

//建立Bean執行個體對象
    @Override
    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException {

        if (logger.isDebugEnabled()) {
            logger.debug("Creating instance of bean '" + beanName + "'");
        }
        RootBeanDefinition mbdToUse = mbd;

        // Make sure bean class is actually resolved at this point, and
        // clone the bean definition in case of a dynamically resolved Class
        // which cannot be stored in the shared merged bean definition.
        //判斷需要建立的Bean是否可以執行個體化,即是否可以通過目前的類加載器加載
        Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
        if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
            mbdToUse = new RootBeanDefinition(mbd);
            mbdToUse.setBeanClass(resolvedClass);
        }

        // Prepare method overrides.
        //校驗和準備Bean中的方法覆寫
        try {
            mbdToUse.prepareMethodOverrides();
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                    beanName, "Validation of method overrides failed", ex);
        }

        try {
            // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
            //如果Bean配置了初始化前和初始化後的處理器,則試圖傳回一個需要建立Bean的代理對象
            Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
            if (bean != null) {
                return bean;
            }
        }
        catch (Throwable ex) {
            throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                    "BeanPostProcessor before instantiation of bean failed", ex);
        }

        try {
            //建立Bean的入口
            Object beanInstance = doCreateBean(beanName, mbdToUse, args);
            if (logger.isDebugEnabled()) {
                logger.debug("Finished creating instance of bean '" + beanName + "'");
            }
            return beanInstance;
        }
        catch (BeanCreationException ex) {
            // A previously detected exception with proper bean creation context already...
            throw ex;
        }
        catch (ImplicitlyAppearedSingletonException ex) {
            // An IllegalStateException to be communicated up to DefaultSingletonBeanRegistry...
            throw ex;
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
        }
    }
           

這裡 doCreateBean是入口

//真正建立Bean的方法
    protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
            throws BeanCreationException {

        // Instantiate the bean.
        //封裝被建立的Bean對象
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        if (instanceWrapper == null) {
            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.
        //調用PostProcessor後置處理器
        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    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.
        //向容器中緩存單例模式的Bean對象,以防循環引用
        boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                isSingletonCurrentlyInCreation(beanName));
        if (earlySingletonExposure) {
            if (logger.isDebugEnabled()) {
                logger.debug("Eagerly caching bean '" + beanName +
                        "' to allow for resolving potential circular references");
            }
            //這裡是一個匿名内部類,為了防止循環引用,盡早持有對象的引用
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        }

        // Initialize the bean instance.
        //Bean對象的初始化,依賴注入在此觸發
        //這個exposedObject在初始化完成之後傳回作為依賴注入完成後的Bean
        Object exposedObject = bean;
        try {
            //将Bean執行個體對象封裝,并且Bean定義中配置的屬性值指派給執行個體對象
            populateBean(beanName, mbd, instanceWrapper);
            //初始化Bean對象
            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) {
            //擷取指定名稱的已注冊的單例模式Bean對象
            Object earlySingletonReference = getSingleton(beanName, false);
            if (earlySingletonReference != null) {
                //根據名稱擷取的已注冊的Bean和正在執行個體化的Bean是同一個
                if (exposedObject == bean) {
                    //目前執行個體化的Bean初始化完成
                    exposedObject = earlySingletonReference;
                }
                //目前Bean依賴其他Bean,并且當發生循環引用時不允許新建立執行個體對象
                else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                    String[] dependentBeans = getDependentBeans(beanName);
                    Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                    //擷取目前Bean所依賴的其他Bean
                    for (String dependentBean : dependentBeans) {
                        //對依賴Bean進行類型檢查
                        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.");
                    }
                }
            }
        }
           

通過對方法源碼的分析, 我們看到具體的依賴注入實作在以下兩個方法中:

(1).createBeanInstance: 生成 Bean 所包含的 java 對象執行個體。

(2).populateBean : 對 Bean 屬性的依賴注入進行處理。

下面繼續分析這兩個方法的代碼實作。

4、 createBeanInstance 方法建立 Bean 的 java 執行個體對象:

在 createBeanInstance 方法中, 根據指定的初始化政策, 使用靜态工廠、 工廠方法或者容器的自動

裝配特性生成 java 執行個體對象, 建立對象的源碼如下:

//建立Bean的執行個體對象
    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
        // Make sure bean class is actually resolved at this point.
        //檢查确認Bean是可執行個體化的
        Class<?> beanClass = resolveBeanClass(mbd, beanName);

        //使用工廠方法對Bean進行執行個體化
        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);
        }

        if (mbd.getFactoryMethodName() != null)  {
            //調用工廠方法執行個體化
            return instantiateUsingFactoryMethod(beanName, mbd, args);
        }

        // Shortcut when re-creating the same 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);
            }
        }

        // Need to determine the constructor...
        //使用Bean的構造方法進行執行個體化
        Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
        if (ctors != null ||
                mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
                mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
            //使用容器的自動裝配特性,調用比對的構造方法執行個體化
            return autowireConstructor(beanName, mbd, ctors, args);
        }

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


    /**
     * Instantiate the given bean using its default constructor.
     * @param beanName the name of the bean
     * @param mbd the bean definition for the bean
     * @return a BeanWrapper for the new instance
     */
    //使用預設的無參構造方法執行個體化Bean對象
    protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
        try {
            Object beanInstance;
            final BeanFactory parent = this;
            //擷取系統的安全管理接口,JDK标準的安全管理API
            if (System.getSecurityManager() != null) {
                //這裡是一個匿名内置類,根據執行個體化政策建立執行個體對象
                beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
                        getInstantiationStrategy().instantiate(mbd, beanName, parent),
                        getAccessControlContext());
            }
            else {
                //将執行個體化的對象封裝起來
                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 的執行個體化相當比較清

楚, 調用相應的工廠方法或者參數比對的構造方法即可完成執行個體化對象的工作, 但是對于我們最常使用

的預設無參構造方法就需要使用相應的初始化政策(JDK 的反射機制或者 CGLIB)來進行初始化了, 在方

法 getInstantiationStrategy().instantiate()中就具體實作類使用初始政策執行個體化對象。

5、 SimpleInstantiationStrategy 類使用預設的無參構造方法建立 Bean 執行個體化對象:

在 使 用 默 認 的 無 參 構 造 方 法 創 建 Bean 的 實 例 化 對 象 時 , 方 法

getInstantiationStrategy().instantiate()調用了 SimpleInstantiationStrategy 類中的實

例化 Bean 的方法, 其源碼如下:

//使用初始化政策執行個體化Bean對象
    @Override
    public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
        // Don't override the class with CGLIB if no overrides.
        //如果Bean定義中沒有方法覆寫,則就不需要CGLIB父類類的方法
        if (!bd.hasMethodOverrides()) {
            Constructor<?> constructorToUse;
            synchronized (bd.constructorArgumentLock) {
                //擷取對象的構造方法或工廠方法
                constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
                //如果沒有構造方法且沒有工廠方法
                if (constructorToUse == null) {
                    //使用JDK的反射機制,判斷要執行個體化的Bean是否是接口
                    final Class<?> clazz = bd.getBeanClass();
                    if (clazz.isInterface()) {
                        throw new BeanInstantiationException(clazz, "Specified class is an interface");
                    }
                    try {
                        if (System.getSecurityManager() != null) {
                            //這裡是一個匿名内置類,使用反射機制擷取Bean的構造方法
                            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);
                    }
                }
            }
            //使用BeanUtils執行個體化,通過反射機制調用”構造方法.newInstance(arg)”來進行執行個體化
            return BeanUtils.instantiateClass(constructorToUse);
        }
        else {
            // Must generate CGLIB subclass.
            //使用CGLIB來執行個體化對象
            return instantiateWithMethodInjection(bd, beanName, owner);
        }
    }
           

通過上面的代碼分析, 我們看到了如果 Bean 有方法被覆寫了, 則使用 JDK 的反射機制進行執行個體化, 否

則, 使用 CGLIB 進行執行個體化。

instantiateWithMethodInjection 方 法 調 用 SimpleInstantiationStrategy 的 子 類

CglibSubclassingInstantiationStrategy 使用 CGLIB 來進行初始化, 其源碼如下:

//使用CGLIB進行Bean對象執行個體化
        public Object instantiate(@Nullable Constructor<?> ctor, @Nullable Object... args) {
            //建立代理子類
            Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
            Object instance;
            if (ctor == null) {
                instance = BeanUtils.instantiateClass(subclass);
            }
            else {
                try {
                    Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
                    instance = enhancedSubclassConstructor.newInstance(args);
                }
                catch (Exception ex) {
                    throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
                            "Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
                }
            }
            // SPR-10785: set callbacks directly on the instance instead of in the
            // enhanced class (via the Enhancer) in order to avoid memory leaks.
            Factory factory = (Factory) instance;
            factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
                    new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
                    new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
            return instance;
        }

        /**
         * Create an enhanced subclass of the bean class for the provided bean
         * definition, using CGLIB.
         */
        private Class<?> createEnhancedSubclass(RootBeanDefinition beanDefinition) {
            //CGLIB中的類
            Enhancer enhancer = new Enhancer();
            //将Bean本身作為其基類
            enhancer.setSuperclass(beanDefinition.getBeanClass());
            enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
            if (this.owner instanceof ConfigurableBeanFactory) {
                ClassLoader cl = ((ConfigurableBeanFactory) this.owner).getBeanClassLoader();
                enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(cl));
            }
            enhancer.setCallbackFilter(new MethodOverrideCallbackFilter(beanDefinition));
            enhancer.setCallbackTypes(CALLBACK_TYPES);
            //使用CGLIB的createClass方法生成執行個體對象
            return enhancer.createClass();
        }
    }
           

CGLIB 是一個常用的位元組碼生成器的類庫, 它提供了一系列 API 實作 java 位元組碼的生成和轉換功能。

我們在學習 JDK 的動态代理時都知道, JDK 的動态代理隻能針對接口, 如果一個類沒有實作任何接口,

要對其進行動态代理隻能使用 CGLIB。

6、 populateBean 方法對 Bean 屬性的依賴注入:

在第 3 步的分析中我們已經了解到 Bean 的依賴注入分為以下兩個過程:

(1).createBeanInstance: 生成 Bean 所包含的 Java 對象執行個體。

(2).populateBean: 對 Bean 屬性的依賴注入進行處理。

上面我們已經分析了容器初始化生成 Bean 所包含的 Java 執行個體對象的過程, 現在我們繼續分析生成對

象後, Spring IOC 容器是如何将 Bean 的屬性依賴關系注入 Bean 執行個體對象中并設定好的, 屬性依賴注

入的代碼如下:

/**
     * Populate the bean instance in the given BeanWrapper with the property values
     * from the bean definition.
     * @param beanName the name of the bean
     * @param mbd the bean definition for the bean
     * @param bw BeanWrapper with bean instance
     */

    //将Bean屬性設定到生成的執行個體對象上
    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
        if (bw == null) {
            if (mbd.hasPropertyValues()) {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
            }
            else {
                // Skip property population phase for null instance.
                return;
            }
        }

        // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
        // state of the bean before properties are set. This can be used, for example,
        // to support styles of field injection.
        boolean continueWithPropertyPopulation = true;

        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                        continueWithPropertyPopulation = false;
                        break;
                    }
                }
            }
        }

        if (!continueWithPropertyPopulation) {
            return;
        }
        //擷取容器在解析Bean定義資源時為BeanDefiniton中設定的屬性值
        PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

        //對依賴注入處理,首先處理autowiring自動裝配的依賴注入
        if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
                mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
            MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

            // Add property values based on autowire by name if applicable.
            //根據Bean名稱進行autowiring自動裝配處理
            if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
                autowireByName(beanName, mbd, bw, newPvs);
            }

            // Add property values based on autowire by type if applicable.
            //根據Bean類型進行autowiring自動裝配處理
            if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
                autowireByType(beanName, mbd, bw, newPvs);
            }

            pvs = newPvs;
        }

        //對非autowiring的屬性進行依賴注入處理

        boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
        boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

        if (hasInstAwareBpps || needsDepCheck) {
            if (pvs == null) {
                pvs = mbd.getPropertyValues();
            }
            PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            if (hasInstAwareBpps) {
                for (BeanPostProcessor bp : getBeanPostProcessors()) {
                    if (bp instanceof InstantiationAwareBeanPostProcessor) {
                        InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                        pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                        if (pvs == null) {
                            return;
                        }
                    }
                }
            }
            if (needsDepCheck) {
                checkDependencies(beanName, mbd, filteredPds, pvs);
            }
        }

        if (pvs != null) {
            //對屬性進行注入
            applyPropertyValues(beanName, mbd, bw, pvs);
        }
    }

    /**
     * Apply the given property values, resolving any runtime references
     * to other beans in this bean factory. Must use deep copy, so we
     * don't permanently modify this property.
     * @param beanName the bean name passed for better exception information
     * @param mbd the merged bean definition
     * @param bw the BeanWrapper wrapping the target object
     * @param pvs the new property values
     */
    //解析并注入依賴屬性的過程
    protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
        if (pvs.isEmpty()) {
            return;
        }

        //封裝屬性值
        MutablePropertyValues mpvs = null;
        List<PropertyValue> original;

        if (System.getSecurityManager() != null) {
            if (bw instanceof BeanWrapperImpl) {
                //設定安全上下文,JDK安全機制
                ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
            }
        }

        if (pvs instanceof MutablePropertyValues) {
            mpvs = (MutablePropertyValues) pvs;
            //屬性值已經轉換
            if (mpvs.isConverted()) {
                // Shortcut: use the pre-converted values as-is.
                try {
                    //為執行個體化對象設定屬性值
                    bw.setPropertyValues(mpvs);
                    return;
                }
                catch (BeansException ex) {
                    throw new BeanCreationException(
                            mbd.getResourceDescription(), beanName, "Error setting property values", ex);
                }
            }
            //擷取屬性值對象的原始類型值
            original = mpvs.getPropertyValueList();
        }
        else {
            original = Arrays.asList(pvs.getPropertyValues());
        }

        //擷取使用者自定義的類型轉換
        TypeConverter converter = getCustomTypeConverter();
        if (converter == null) {
            converter = bw;
        }
        //建立一個Bean定義屬性值解析器,将Bean定義中的屬性值解析為Bean執行個體對象的實際值
        BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

        // Create a deep copy, resolving any references for values.

        //為屬性的解析值建立一個拷貝,将拷貝的資料注入到執行個體對象中
        List<PropertyValue> deepCopy = new ArrayList<>(original.size());
        boolean resolveNecessary = false;
        for (PropertyValue pv : original) {
            //屬性值不需要轉換
            if (pv.isConverted()) {
                deepCopy.add(pv);
            }
            //屬性值需要轉換
            else {
                String propertyName = pv.getName();
                //原始的屬性值,即轉換之前的屬性值
                Object originalValue = pv.getValue();
                //轉換屬性值,例如将引用轉換為IOC容器中執行個體化對象引用
                Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
                //轉換之後的屬性值
                Object convertedValue = resolvedValue;
                //屬性值是否可以轉換
                boolean convertible = bw.isWritableProperty(propertyName) &&
                        !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
                if (convertible) {
                    //使用使用者自定義的類型轉換器轉換屬性值
                    convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
                }
                // Possibly store converted value in merged bean definition,
                // in order to avoid re-conversion for every created bean instance.
                //存儲轉換後的屬性值,避免每次屬性注入時的轉換工作
                if (resolvedValue == originalValue) {
                    if (convertible) {
                        //設定屬性轉換之後的值
                        pv.setConvertedValue(convertedValue);
                    }
                    deepCopy.add(pv);
                }
                //屬性是可轉換的,且屬性原始值是字元串類型,且屬性的原始類型值不是
                //動态生成的字元串,且屬性的原始值不是集合或者數組類型
                else if (convertible && originalValue instanceof TypedStringValue &&
                        !((TypedStringValue) originalValue).isDynamic() &&
                        !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
                    pv.setConvertedValue(convertedValue);
                    //重新封裝屬性的值
                    deepCopy.add(pv);
                }
                else {
                    resolveNecessary = true;
                    deepCopy.add(new PropertyValue(pv, convertedValue));
                }
            }
        }
        if (mpvs != null && !resolveNecessary) {
            //标記屬性值已經轉換過
            mpvs.setConverted();
        }

        // Set our (possibly massaged) deep copy.
        //進行屬性依賴注入
        try {
            bw.setPropertyValues(new MutablePropertyValues(deepCopy));
        }
        catch (BeansException ex) {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Error setting property values", ex);
        }
    }
           

分析上述代碼, 我們可以看出, 對屬性的注入過程分以下兩種情況:

(1).屬性值類型不需要轉換時, 不需要解析屬性值, 直接準備進行依賴注入。

(2).屬性值需要進行類型轉換時, 如對其他對象的引用等, 首先需要解析屬性值, 然後對解析後的屬性

值進行依賴注入。

對屬性值的解析是在 BeanDefinitionValueResolver 類中的 resolveValueIfNecessary 方法中進

行的, 對屬性值的依賴注入是通過 bw.setPropertyValues 方法實作的, 在分析屬性值的依賴注入之

前, 我們先分析一下對屬性值的解析過程。

7、 BeanDefinitionValueResolver 解析屬性值:

當容器在對屬性進行依賴注入時, 如果發現屬性值需要進行類型轉換, 如屬性值是容器中另一個 Bean

執行個體對象的引用, 則容器首先需要根據屬性值解析出所引用的對象, 然後才能将該引用對象注入到目标

執行個體對象的屬性上去, 對屬性進行解析的由 resolveValueIfNecessary 方法實作, 其源碼如下:

/**
     * Given a PropertyValue, return a value, resolving any references to other
     * beans in the factory if necessary. The value could be:
     * <li>A BeanDefinition, which leads to the creation of a corresponding
     * new bean instance. Singleton flags and names of such "inner beans"
     * are always ignored: Inner beans are anonymous prototypes.
     * <li>A RuntimeBeanReference, which must be resolved.
     * <li>A ManagedList. This is a special collection that may contain
     * RuntimeBeanReferences or Collections that will need to be resolved.
     * <li>A ManagedSet. May also contain RuntimeBeanReferences or
     * Collections that will need to be resolved.
     * <li>A ManagedMap. In this case the value may be a RuntimeBeanReference
     * or Collection that will need to be resolved.
     * <li>An ordinary object or {@code null}, in which case it's left alone.
     * @param argName the name of the argument that the value is defined for
     * @param value the value object to resolve
     * @return the resolved object
     */
    //解析屬性值,對注入類型進行轉換
    @Nullable
    public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {
        // We must check each value to see whether it requires a runtime reference
        // to another bean to be resolved.
        //對引用類型的屬性進行解析
        if (value instanceof RuntimeBeanReference) {
            RuntimeBeanReference ref = (RuntimeBeanReference) value;
            //調用引用類型屬性的解析方法
            return resolveReference(argName, ref);
        }
        //對屬性值是引用容器中另一個Bean名稱的解析
        else if (value instanceof RuntimeBeanNameReference) {
            String refName = ((RuntimeBeanNameReference) value).getBeanName();
            refName = String.valueOf(doEvaluate(refName));
            //從容器中擷取指定名稱的Bean
            if (!this.beanFactory.containsBean(refName)) {
                throw new BeanDefinitionStoreException(
                        "Invalid bean name '" + refName + "' in bean reference for " + argName);
            }
            return refName;
        }
        //對Bean類型屬性的解析,主要是Bean中的内部類
        else if (value instanceof BeanDefinitionHolder) {
            // Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
            BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
            return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
        }
        else if (value instanceof BeanDefinition) {
            // Resolve plain BeanDefinition, without contained name: use dummy name.
            BeanDefinition bd = (BeanDefinition) value;
            String innerBeanName = "(inner bean)" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR +
                    ObjectUtils.getIdentityHexString(bd);
            return resolveInnerBean(argName, innerBeanName, bd);
        }
        //對集合數組類型的屬性解析
        else if (value instanceof ManagedArray) {
            // May need to resolve contained runtime references.
            ManagedArray array = (ManagedArray) value;
            //擷取數組的類型
            Class<?> elementType = array.resolvedElementType;
            if (elementType == null) {
                //擷取數組元素的類型
                String elementTypeName = array.getElementTypeName();
                if (StringUtils.hasText(elementTypeName)) {
                    try {
                        //使用反射機制建立指定類型的對象
                        elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
                        array.resolvedElementType = elementType;
                    }
                    catch (Throwable ex) {
                        // Improve the message by showing the context.
                        throw new BeanCreationException(
                                this.beanDefinition.getResourceDescription(), this.beanName,
                                "Error resolving array type for " + argName, ex);
                    }
                }
                //沒有擷取到數組的類型,也沒有擷取到數組元素的類型
                //則直接設定數組的類型為Object
                else {
                    elementType = Object.class;
                }
            }
            //建立指定類型的數組
            return resolveManagedArray(argName, (List<?>) value, elementType);
        }
        //解析list類型的屬性值
        else if (value instanceof ManagedList) {
            // May need to resolve contained runtime references.
            return resolveManagedList(argName, (List<?>) value);
        }
        //解析set類型的屬性值
        else if (value instanceof ManagedSet) {
            // May need to resolve contained runtime references.
            return resolveManagedSet(argName, (Set<?>) value);
        }
        //解析map類型的屬性值
        else if (value instanceof ManagedMap) {
            // May need to resolve contained runtime references.
            return resolveManagedMap(argName, (Map<?, ?>) value);
        }
        //解析props類型的屬性值,props其實就是key和value均為字元串的map
        else if (value instanceof ManagedProperties) {
            Properties original = (Properties) value;
            //建立一個拷貝,用于作為解析後的傳回值
            Properties copy = new Properties();
            original.forEach((propKey, propValue) -> {
                if (propKey instanceof TypedStringValue) {
                    propKey = evaluate((TypedStringValue) propKey);
                }
                if (propValue instanceof TypedStringValue) {
                    propValue = evaluate((TypedStringValue) propValue);
                }
                if (propKey == null || propValue == null) {
                    throw new BeanCreationException(
                            this.beanDefinition.getResourceDescription(), this.beanName,
                            "Error converting Properties key/value pair for " + argName + ": resolved to null");
                }
                copy.put(propKey, propValue);
            });
            return copy;
        }
        //解析字元串類型的屬性值
        else if (value instanceof TypedStringValue) {
            // Convert value to target type here.
            TypedStringValue typedStringValue = (TypedStringValue) value;
            Object valueObject = evaluate(typedStringValue);
            try {
                //擷取屬性的目标類型
                Class<?> resolvedTargetType = resolveTargetType(typedStringValue);
                if (resolvedTargetType != null) {
                    //對目标類型的屬性進行解析,遞歸調用
                    return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
                }
                //沒有擷取到屬性的目标對象,則按Object類型傳回
                else {
                    return valueObject;
                }
            }
            catch (Throwable ex) {
                // Improve the message by showing the context.
                throw new BeanCreationException(
                        this.beanDefinition.getResourceDescription(), this.beanName,
                        "Error converting typed String value for " + argName, ex);
            }
        }
        else if (value instanceof NullBean) {
            return null;
        }
        else {
            return evaluate(value);
        }
    }

    /**
     * Resolve a reference to another bean in the factory.
     */
    //解析引用類型的屬性值
    @Nullable
    private Object resolveReference(Object argName, RuntimeBeanReference ref) {
        try {
            Object bean;
            //擷取引用的Bean名稱
            String refName = ref.getBeanName();
            refName = String.valueOf(doEvaluate(refName));
            //如果引用的對象在父類容器中,則從父類容器中擷取指定的引用對象
            if (ref.isToParent()) {
                if (this.beanFactory.getParentBeanFactory() == null) {
                    throw new BeanCreationException(
                            this.beanDefinition.getResourceDescription(), this.beanName,
                            "Can't resolve reference to bean '" + refName +
                            "' in parent factory: no parent factory available");
                }
                bean = this.beanFactory.getParentBeanFactory().getBean(refName);
            }
            //從目前的容器中擷取指定的引用Bean對象,如果指定的Bean沒有被執行個體化
            //則會遞歸觸發引用Bean的初始化和依賴注入
            else {
                bean = this.beanFactory.getBean(refName);
                //将目前執行個體化對象的依賴引用對象
                this.beanFactory.registerDependentBean(refName, this.beanName);
            }
            if (bean instanceof NullBean) {
                bean = null;
            }
            return bean;
        }
        catch (BeansException ex) {
            throw new BeanCreationException(
                    this.beanDefinition.getResourceDescription(), this.beanName,
                    "Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
        }
    }

    /**
     * For each element in the managed array, resolve reference if necessary.
     */
    //解析array類型的屬性
    private Object resolveManagedArray(Object argName, List<?> ml, Class<?> elementType) {
        //建立一個指定類型的數組,用于存放和傳回解析後的數組
        Object resolved = Array.newInstance(elementType, ml.size());
        for (int i = ; i < ml.size(); i++) {
            //遞歸解析array的每一個元素,并将解析後的值設定到resolved數組中,索引為i
            Array.set(resolved, i,
                    resolveValueIfNecessary(new KeyedArgName(argName, i), ml.get(i)));
        }
        return resolved;
    }
           

通過上面的代碼分析, 我們明白了 Spring 是如何将引用類型, 内部類以及集合類型等屬性進行解析的,

屬性值解析完成後就可以進行依賴注入了, 依賴注入的過程就是 Bean 對象執行個體設定到它所依賴的 Bean

對象屬性上去, 在第 6 步中我們已經說過, 依賴注入是通過 bw.setPropertyValues 方法實作的, 該方法也使用了委托模式, 在 BeanWrapper 接口中至少定義了方法聲明, 依賴注入的具體實作交由其實

現類 BeanWrapperImpl 來完成, 下面我們就分析依 BeanWrapperImpl 中賴注入相關的源碼。

回到AbstractAutowireCapableBeanFactory.applyPropertyValues方法

有一段bw.setPropertyValues(mpvs);從這裡看

8、 BeanWrapperImpl 對 Bean 屬性的依賴注入:

BeanWrapperImpl 類主要是對容器中完成初始化的 Bean 執行個體對象進行屬性的依賴注入, 即把 Bean 對象設定到它所依賴的另一個 Bean 的屬性中去。 然而, BeanWrapperImpl 中的注入方法實際上由

AbstractNestablePropertyAccessor 來實作的, 其相關源碼如下:

@Override
    public void setPropertyValues(PropertyValues pvs) throws BeansException {
        setPropertyValues(pvs, false, false);
    }

    @Override
    public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown, boolean ignoreInvalid)
            throws BeansException {

        List<PropertyAccessException> propertyAccessExceptions = null;
        List<PropertyValue> propertyValues = (pvs instanceof MutablePropertyValues ?
                ((MutablePropertyValues) pvs).getPropertyValueList() : Arrays.asList(pvs.getPropertyValues()));
        for (PropertyValue pv : propertyValues) {
            try {
                // This method may throw any BeansException, which won't be caught
                // here, if there is a critical failure such as no matching field.
                // We can attempt to deal only with less serious exceptions.
                setPropertyValue(pv);
            }
            catch (NotWritablePropertyException ex) {
                if (!ignoreUnknown) {
                    throw ex;
                }
                // Otherwise, just ignore it and continue...
            }
            catch (NullValueInNestedPathException ex) {
                if (!ignoreInvalid) {
                    throw ex;
                }
                // Otherwise, just ignore it and continue...
            }
            catch (PropertyAccessException ex) {
                if (propertyAccessExceptions == null) {
                    propertyAccessExceptions = new LinkedList<>();
                }
                propertyAccessExceptions.add(ex);
            }
        }

        // If we encountered individual exceptions, throw the composite exception.
        if (propertyAccessExceptions != null) {
            PropertyAccessException[] paeArray =
                    propertyAccessExceptions.toArray(new PropertyAccessException[propertyAccessExceptions.size()]);
            throw new PropertyBatchUpdateException(paeArray);
        }
    }

    @Override
    public void setPropertyValue(PropertyValue pv) throws BeansException {
        setPropertyValue(pv.getName(), pv.getValue());
    }

    @Override
    public void setPropertyValue(String propertyName, @Nullable Object value) throws BeansException {
        AbstractNestablePropertyAccessor nestedPa;
        try {
            nestedPa = getPropertyAccessorForPropertyPath(propertyName);
        }
        catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Nested property in path '" + propertyName + "' does not exist", ex);
        }
        PropertyTokenHolder tokens = getPropertyNameTokens(getFinalPath(nestedPa, propertyName));
        nestedPa.setPropertyValue(tokens, new PropertyValue(propertyName, value));
    }

    //實作屬性依賴注入功能
    protected void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
        if (tokens.keys != null) {
            processKeyedProperty(tokens, pv);
        }
        else {
            processLocalProperty(tokens, pv);
        }
    }

    //實作屬性依賴注入功能
    @SuppressWarnings("unchecked")
    private void processKeyedProperty(PropertyTokenHolder tokens, PropertyValue pv) {
        //調用屬性的getter(readerMethod)方法,擷取屬性的值
        Object propValue = getPropertyHoldingValue(tokens);
        PropertyHandler ph = getLocalPropertyHandler(tokens.actualName);
        if (ph == null) {
            throw new InvalidPropertyException(
                    getRootClass(), this.nestedPath + tokens.actualName, "No property handler found");
        }
        Assert.state(tokens.keys != null, "No token keys");
        String lastKey = tokens.keys[tokens.keys.length - ];

        //注入array類型的屬性值
        if (propValue.getClass().isArray()) {
            Class<?> requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(lastKey);
            Object oldValue = null;
            try {
                if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(),
                        requiredType, ph.nested(tokens.keys.length));
                //擷取集合類型屬性的長度
                int length = Array.getLength(propValue);
                if (arrayIndex >= length && arrayIndex < this.autoGrowCollectionLimit) {
                    Class<?> componentType = propValue.getClass().getComponentType();
                    Object newArray = Array.newInstance(componentType, arrayIndex + );
                    System.arraycopy(propValue, , newArray, , length);
                    setPropertyValue(tokens.actualName, newArray);
                    //調用屬性的getter(readerMethod)方法,擷取屬性的值
                    propValue = getPropertyValue(tokens.actualName);
                }
                //将屬性的值指派給數組中的元素
                Array.set(propValue, arrayIndex, convertedValue);
            }
            catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
                        "Invalid array index in property path '" + tokens.canonicalName + "'", ex);
            }
        }

        //注入list類型的屬性值
        else if (propValue instanceof List) {
            //擷取list集合的類型
            Class<?> requiredType = ph.getCollectionType(tokens.keys.length);
            List<Object> list = (List<Object>) propValue;
            //擷取list集合的size
            int index = Integer.parseInt(lastKey);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            //擷取list解析後的屬性值
            Object convertedValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(),
                    requiredType, ph.nested(tokens.keys.length));
            int size = list.size();
            //如果list的長度大于屬性值的長度,則多餘的元素指派為null
            if (index >= size && index < this.autoGrowCollectionLimit) {
                for (int i = size; i < index; i++) {
                    try {
                        list.add(null);
                    }
                    catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
                                "Cannot set element with index " + index + " in List of size " +
                                size + ", accessed using property path '" + tokens.canonicalName +
                                "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            }
            else {
                try {
                    //将值添加到list中
                    list.set(index, convertedValue);
                }
                catch (IndexOutOfBoundsException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
                            "Invalid list index in property path '" + tokens.canonicalName + "'", ex);
                }
            }
        }

        //注入map類型的屬性值
        else if (propValue instanceof Map) {
            //擷取map集合key的類型
            Class<?> mapKeyType = ph.getMapKeyType(tokens.keys.length);
            //擷取map集合value的類型
            Class<?> mapValueType = ph.getMapValueType(tokens.keys.length);
            Map<Object, Object> map = (Map<Object, Object>) propValue;
            // IMPORTANT: Do not pass full property name in here - property editors
            // must not kick in for map keys but rather only for map values.
            TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
            //解析map類型屬性key值
            Object convertedMapKey = convertIfNecessary(null, null, lastKey, mapKeyType, typeDescriptor);
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            // Pass full property name and old value in here, since we want full
            // conversion ability for map values.
            //解析map類型屬性value值
            Object convertedMapValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(),
                    mapValueType, ph.nested(tokens.keys.length));
            //将解析後的key和value值指派給map集合屬性
            map.put(convertedMapKey, convertedMapValue);
        }

        else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
                    "Property referenced in indexed property path '" + tokens.canonicalName +
                    "' is neither an array nor a List nor a Map; returned value was [" + propValue + "]");
        }
    }

    private Object getPropertyHoldingValue(PropertyTokenHolder tokens) {
        // Apply indexes and map keys: fetch value for all keys but the last one.
        Assert.state(tokens.keys != null, "No token keys");
        PropertyTokenHolder getterTokens = new PropertyTokenHolder(tokens.actualName);
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.keys = new String[tokens.keys.length - ];
        System.arraycopy(tokens.keys, , getterTokens.keys, , tokens.keys.length - );

        Object propValue;
        try {
            //擷取屬性值
            propValue = getPropertyValue(getterTokens);
        }
        catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + tokens.canonicalName,
                    "Cannot access indexed value in property referenced " +
                    "in indexed property path '" + tokens.canonicalName + "'", ex);
        }

        if (propValue == null) {
            // null map value case
            if (isAutoGrowNestedPaths()) {
                int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
                getterTokens.canonicalName = tokens.canonicalName.substring(, lastKeyIndex);
                propValue = setDefaultValue(getterTokens);
            }
            else {
                throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + tokens.canonicalName,
                        "Cannot access indexed value in property referenced " +
                        "in indexed property path '" + tokens.canonicalName + "': returned null");
            }
        }
        return propValue;
    }
           

通過對上面注入依賴代碼的分析, 我們已經明白了 Spring IOC 容器是如何将屬性的值注入到 Bean 實

例對象中去的:

(1).對于集合類型的屬性, 将其屬性值解析為目标類型的集合後直接指派給屬性。

(2).對于非集合類型的屬性, 大量使用了 JDK 的反射和内省機制, 通過屬性的 getter 方法(reader

Method)擷取指定屬性注入以前的值, 同時調用屬性的 setter 方法(writer Method)為屬性設定注入

後的值。 看到這裡相信很多人都明白了 Spring 的 setter 注入原理。

Spring源碼分析之依賴注入

至此 Spring IOC 容器對 Bean 定義資源檔案的定位, 載入、 解析和依賴注入已經全部分析完畢, 現在

Spring IOC 容器中管理了一系列靠依賴關系聯系起來的 Bean, 程式不需要應用自己手動建立所需的對

象, Spring IOC 容器會在我們使用的時候自動為我們建立, 并且為我們注入好相關的依賴, 這就是

Spring 核心功能的控制反轉和依賴注入的相關功能。

現在總結一下這些類

BeanDefinition 相當于是儲存在記憶體中的配置檔案,儲存了所有的跟類屬性相關資訊

依賴注入,就是把BeanDefinition中的資訊讀取出來,利用反射機制,或者代理機制建立對象,新建立的對象,不會放到我們印象中的IOC容器中,它存入到另外一個cache容器

Wrapper對原生對象的包裝,通過構造方法存儲原始對象,放入cache的隻是Wrapper

減少代碼侵入,能夠在原生的基礎之上,再進行擴充,監聽器、回調函數、标記資訊

================================================================

原生 Bean: 通過反射或者代理機制建立的Bean

BeanDefinition: 靜态配置檔案的一個記憶體版本,儲存了所有的OOP關系

BeanWrapper: 是原生Bean的包裝,通過構造方法實作包裝,真正操作的是Wrapper

FacoryBean:是Spring中最頂層接口,隻要是通過工廠建立Bean,都要實作FacotryBean