Spring源码解析笔记6——创建bean

继续spring源码笔记4中的doCreateBean方法:

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
        BeanWrapper instanceWrapper = null;

        //如果是单例则需要首先清除缓存。
        if(mbd.isSingleton()) {
            instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
        }

        if(instanceWrapper == null) {

            //根据指定bean使用对应的策略创建新的实例。例如:工厂方法,构造函数注入,简单的初始化。
            /**
                将BeanDefinition转换为BeanWrapper,大概逻辑如下:
                1.如果存在工厂方法,则使用工厂方法进行初始化。
                2.一个类有多个构造函数,每个构造函数都有不同的参数,需要根据参数锁定构造函数并初始化。
                3.如果不存在工厂,也不存在带参数的构造函数,则使用默认的构造函数进行bean初始化。
            **/
            instanceWrapper = this.createBeanInstance(beanName, mbd, args);
        }

        final Object bean = instanceWrapper != null?instanceWrapper.getWrappedInstance():null;
        Class beanType = instanceWrapper != null?instanceWrapper.getWrappedClass():null;
        mbd.resolvedTargetType = beanType;
        Object earlySingletonExposure = mbd.postProcessingLock;
        synchronized(mbd.postProcessingLock) {
            if(!mbd.postProcessed) {
                try {

                    //bean合并后处理,Autowired注解就是通过此方法实现类型的预解析。
                    this.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                } catch (Throwable var17) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", var17);
                }

                mbd.postProcessed = true;
            }
        }

        //是否需要提早曝光:单例&允许循环依赖&当前bean正在创建中,检测循环依赖。
        boolean var20 = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
        if(var20) {
            if(this.logger.isDebugEnabled()) {
                this.logger.debug("Eagerly caching bean \'" + beanName + "\' to allow for resolving potential circular references");
            }

            //为避免后期循环依赖,可以在bean初始化完成前期将创建实例的ObjectFactory加入工厂
            this.addSingletonFactory(beanName, new ObjectFactory() {
                public Object getObject() throws BeansException {

                    //对bean再一次依赖引用,例如AOP就是在此处将advice动态织入bean中,若没有直接返回bean,不做处理。
                    return AbstractAutowireCapableBeanFactory.this.getEarlyBeanReference(beanName, mbd, bean);
                }
            });
        }

        Object exposedObject = bean;

        try {

            //对bean进行填充,将各个属性值注入,其中,可能存在依赖于其他bean的属性,则会递归初始依赖bean。
            this.populateBean(beanName, mbd, instanceWrapper);
            if(exposedObject != null) {
                exposedObject = this.initializeBean(beanName, exposedObject, mbd);
            }
        } catch (Throwable var18) {
            if(var18 instanceof BeanCreationException && beanName.equals(((BeanCreationException)var18).getBeanName())) {
                throw (BeanCreationException)var18;
            }

            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", var18);
        }

        if(var20) {
            Object ex = this.getSingleton(beanName, false);
            //ex只有在检测到有循环依赖的情况下才不为null。
            if(ex != null) {

                //如果exposedObject没有在初始化方法中被改变,即没有被增强。
                if(exposedObject == bean) {
                    exposedObject = ex;
                } else if(!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
                    String[] dependentBeans = this.getDependentBeans(beanName);
                    LinkedHashSet actualDependentBeans = new LinkedHashSet(dependentBeans.length);
                    String[] var12 = dependentBeans;
                    int var13 = dependentBeans.length;

                    for(int var14 = 0; var14 < var13; ++var14) {
                        String dependentBean = var12[var14];

                  //检测依赖。      
                  if(!this.removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                            actualDependentBeans.add(dependentBean);
                        }
                    }

                    //因为bean创建以后其所依赖的bean一定是已经创建的
                    //actualDependentBeans不为空则表示当前bean创建后,其依赖的bean却没有被创建完毕,也就是说存在循环依赖。
                    //也就是说对于prototype的bean,spring解决不了,只能抛异常。
                    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.");
                    }
                }
            }
        }

        try {

            //根据scope注册bean
            //如果配置了destroy-method,这里需要注册以便于在销毁时候调用。
            this.registerDisposableBeanIfNecessary(beanName, bean, mbd);
            return exposedObject;
        } catch (BeanDefinitionValidationException var16) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", var16);
        }
    }

以下根据上面的每一步进行跟踪分析:

  • this.createBeanInstance方法:

    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
    
        //解析bean
        Class beanClass = this.resolveBeanClass(mbd, beanName, new Class[0]);
        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());
    
        //如果工厂方法不为空则使用工厂方法初始化策略。
        } else if(mbd.getFactoryMethodName() != null) {
            return this.instantiateUsingFactoryMethod(beanName, mbd, args);
        } else {
            boolean resolved = false;
            boolean autowireNecessary = false;
            if(args == null) {
                Object ctors = mbd.constructorArgumentLock;
                synchronized(mbd.constructorArgumentLock) {
    
                    //一个类有多个构造函数,每个构造函数都有不同的参数,所以调用前需要先根据参数锁定构造函数或对应的工厂方法。
                    if(mbd.resolvedConstructorOrFactoryMethod != null) {
                        resolved = true;
                        autowireNecessary = mbd.constructorArgumentsResolved;
                    }
                }
            }
    
            //如果已经解析过则使用解析好的构造函数方法不需要再次锁定。
            if(resolved) {
    
                //构造函数自动注入。
                //autowireConstructor是构造函数自动注入。
                //instantiateBean是使用默认构造函数。
                return autowireNecessary?this.autowireConstructor(beanName, mbd, (Constructor[])null, (Object[])null):this.instantiateBean(beanName, mbd);
            } else {
    
                //需要根据参数解析构造函数。
                Constructor[] ctors1 = this.determineConstructorsFromBeanPostProcessors(beanClass, beanName);
                return ctors1 == null && mbd.getResolvedAutowireMode() != 3 && !mbd.hasConstructorArgumentValues() && ObjectUtils.isEmpty(args)?this.instantiateBean(beanName, mbd):this.autowireConstructor(beanName, mbd, ctors1, args);
            }
        }
    }

对于实例的创建Spring中分成了两种情况,一种是通用的实例化,由instantiateBean负责实现,另一种是带有参数的实例化,此过程存在着不确定性,所以在判断参数上做了大量工作,通过autowireConstructor。

1.首先跟踪一下带参数的实例化autowireConstructor。

//autowireConstructor方法源码:
protected BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd, Constructor[] ctors, Object[] explicitArgs) {
        return (new ConstructorResolver(this)).autowireConstructor(beanName, mbd, ctors, explicitArgs);
}

继续跟踪:

public BeanWrapper autowireConstructor(final String beanName, final RootBeanDefinition mbd, Constructor[] chosenCtors, Object[] explicitArgs) {
        BeanWrapperImpl bw = new BeanWrapperImpl();
        this.beanFactory.initBeanWrapper(bw);
        final Constructor constructorToUse = null;
        ConstructorResolver.ArgumentsHolder argsHolderToUse = null;
        final Object[] argsToUse = null;

        //explicitArgs通过getBean方法传入。
        //如果getBean方法调用的时候指定方法参数那么直接使用。
        /**
            BeanFactory中存在这样的方法:Object getBean(String name,Object …… args) throws BeansException
            在获取bean时,用户不但可以指定bean的名称还可以指定bean所对应类的构造函数或者工厂方法的方法参数,用于静态工厂方法调用。
            这里需要给定完全匹配的参数,所以如果explicitArgs不为空,则可确定构造函数参数。
        **/
        if(explicitArgs != null) {
            argsToUse = explicitArgs;
        } else {

            //如果在getBean方法时候没有指定则尝试从配置文件中解析。
            Object[] ex = null;
            Object ctorToUse = mbd.constructorArgumentLock;

            //尝试从缓存中获取。
            synchronized(mbd.constructorArgumentLock) {

                //缓存中缓存的可能是参数的初始类型,所有此处需要经过类型转换器的过滤确保参数类型与对应的构造函数参数类型完全对应。
                //例如:构造函数要求是int类型,但是原始参数值可能是String类型的“1”.
                constructorToUse = (Constructor)mbd.resolvedConstructorOrFactoryMethod;
                if(constructorToUse != null && mbd.constructorArgumentsResolved) {

                    //从缓存中获取。
                    argsToUse = mbd.resolvedConstructorArguments;
                    if(argsToUse == null) {

                        //配置的构造函数参数。
                        ex = mbd.preparedConstructorArguments;
                    }
                }
            }

            //如果缓存中存在
            if(ex != null) {

                //解析参数类型,如给定方法的构造函数A(int,int)通过此方法后就会把配置中的("1","1")转换为(1,1)
                //缓存中的值有可能是原始值,也可能是最终值。
                argsToUse = this.resolvePreparedArguments(beanName, mbd, bw, constructorToUse, ex);
            }
        }

        //没有缓存。
        if(constructorToUse == null) {
            boolean var28 = chosenCtors != null || mbd.getResolvedAutowireMode() == 3;
            ConstructorArgumentValues var29 = null;
            int argumentsToUse;
            if(explicitArgs != null) {
                argumentsToUse = explicitArgs.length;
            } else {

                //提取配置文件中配置的构造函数参数。
                ConstructorArgumentValues candidates = mbd.getConstructorArgumentValues();

                //用于承载解析后的构造函数参数的值。
                var29 = new ConstructorArgumentValues();

                //能解析到的参数个数
                argumentsToUse = this.resolveConstructorArguments(beanName, mbd, bw, candidates, var29);
            }

            Constructor[] var31 = chosenCtors;
            if(chosenCtors == null) {
                Class minTypeDiffWeight = mbd.getBeanClass();

                try {
                    var31 = mbd.isNonPublicAccessAllowed()?minTypeDiffWeight.getDeclaredConstructors():minTypeDiffWeight.getConstructors();
                } catch (Throwable var25) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Resolution of declared constructors on bean Class [" + minTypeDiffWeight.getName() + "] from ClassLoader [" + minTypeDiffWeight.getClassLoader() + "] failed", var25);
                }
            }

            //排序给定的构造函数,public构造函数优先,按参数数量降序。
            AutowireUtils.sortConstructors(var31);
            int var32 = 2147483647;
            LinkedHashSet ambiguousConstructors = null;
            LinkedList causes = null;
            Constructor[] ex1 = var31;
            int var17 = var31.length;

            for(int cause = 0; cause < var17; ++cause) {
                Constructor candidate = ex1[cause];
                Class[] paramTypes = candidate.getParameterTypes();

                //如果已经找到选用的构造函数或者需要的参数个数小于当前的构造函数参数个数则终止,因为已经按照参数个数降序排列。
                if(constructorToUse != null && argsToUse.length > paramTypes.length) {
                    break;
                }

                if(paramTypes.length >= argumentsToUse) {
                    ConstructorResolver.ArgumentsHolder argsHolder;
                    if(var29 != null) {
                        try {

                            //注释上获取参数名称
                            String[] typeDiffWeight = ConstructorResolver.ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length);
                            if(typeDiffWeight == null) {

                                //获取参数名称探索器。
                                ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                                if(pnd != null) {

                                    //获取指定构造函数的参数名。
                                    typeDiffWeight = pnd.getParameterNames(candidate);
                                }
                            }

                            //根据名称和数据类型创建参数持有者。
                            argsHolder = this.createArgumentArray(beanName, mbd, var29, bw, paramTypes, typeDiffWeight, this.getUserDeclaredConstructor(candidate), var28);
                        } catch (UnsatisfiedDependencyException var26) {
                            if(this.beanFactory.logger.isTraceEnabled()) {
                                this.beanFactory.logger.trace("Ignoring constructor [" + candidate + "] of bean \'" + beanName + "\': " + var26);
                            }

                            if(causes == null) {
                                causes = new LinkedList();
                            }

                            causes.add(var26);
                            continue;
                        }
                    } else {
                        if(paramTypes.length != explicitArgs.length) {
                            continue;
                        }

                        //构造函数没有参数的情况下。
                        argsHolder = new ConstructorResolver.ArgumentsHolder(explicitArgs);
                    }

                    //探测是否有不确定性的构造函数存在,例如不同构造函数的参数为父子关系。
                    int var36 = mbd.isLenientConstructorResolution()?argsHolder.getTypeDifferenceWeight(paramTypes):argsHolder.getAssignabilityWeight(paramTypes);

                    //如果它代表着当前最接近的匹配则选择作为构造器。
                    if(var36 < var32) {
                        constructorToUse = candidate;
                        argsHolderToUse = argsHolder;
                        argsToUse = argsHolder.arguments;
                        var32 = var36;
                        ambiguousConstructors = null;
                    } else if(constructorToUse != null && var36 == var32) {
                        if(ambiguousConstructors == null) {
                            ambiguousConstructors = new LinkedHashSet();
                            ambiguousConstructors.add(constructorToUse);
                        }

                        ambiguousConstructors.add(candidate);
                    }
                }
            }

            if(constructorToUse == null) {
                if(causes == null) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
                }

                UnsatisfiedDependencyException var33 = (UnsatisfiedDependencyException)causes.removeLast();
                Iterator var34 = causes.iterator();

                while(var34.hasNext()) {
                    Exception var35 = (Exception)var34.next();
                    this.beanFactory.onSuppressedException(var35);
                }

                throw var33;
            }

            if(ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Ambiguous constructor matches found in bean \'" + beanName + "\' (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " + ambiguousConstructors);
            }

            if(explicitArgs == null) {

                //将解析的构造函数加入缓存。
                argsHolderToUse.storeCache(mbd, constructorToUse);
            }
        }

        try {
            Object var30;
            if(System.getSecurityManager() != null) {
                var30 = AccessController.doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        return ConstructorResolver.this.beanFactory.getInstantiationStrategy().instantiate(mbd, beanName, ConstructorResolver.this.beanFactory, constructorToUse, argsToUse);
                    }
                }, this.beanFactory.getAccessControlContext());
            } else {
                var30 = this.beanFactory.getInstantiationStrategy().instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
            }

            //将构建的实例加入BeanWrapper中。
            bw.setBeanInstance(var30);
            return bw;
        } catch (Throwable var24) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean instantiation via constructor failed", var24);
        }
    }

2.不带参数的实例化方法:instantiateBean

//源码如下
/**
    在有参的实例构造中,Spring把精力都放在了构造函数以及参数的匹配上了。
    所以在没有参数的实例构造中,只是直接调用了**实例化策略**进行实例化。
**/
 protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
        try {
            Object ex;
            if(System.getSecurityManager() != null) {
                ex = AccessController.doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        return AbstractAutowireCapableBeanFactory.this.getInstantiationStrategy().instantiate(mbd, beanName, AbstractAutowireCapableBeanFactory.this);
                    }
                }, this.getAccessControlContext());
            } else {
                ex = this.getInstantiationStrategy().instantiate(mbd, beanName, this);
            }

            BeanWrapperImpl bw = new BeanWrapperImpl(ex);
            this.initBeanWrapper(bw);
            return bw;
        } catch (Throwable var6) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", var6);
        }
    }

spring并没有直接利用反射的方法直接构造实例对象,而是在反射之前加了判断,也就是实例化策略

public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {

        /**
            如果有需要覆盖或者动态替换的方法则需要使用cglib进行动态代理,因为可以在创建代理的同时将动态方法织入类中。
            如果没有需要动态改变的方法,直接反射就可以了。
        **/
        if(bd.getMethodOverrides().isEmpty()) {
            Object var5 = bd.constructorArgumentLock;
            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 = (Constructor)AccessController.doPrivileged(new PrivilegedExceptionAction() {
                                public Constructor run() throws Exception {
                                    return clazz.getDeclaredConstructor((Class[])null);
                                }
                            });
                        } else {
                            constructorToUse = clazz.getDeclaredConstructor((Class[])null);
                        }

                        bd.resolvedConstructorOrFactoryMethod = constructorToUse;
                    } catch (Throwable var9) {
                        throw new BeanInstantiationException(clazz, "No default constructor found", var9);
                    }
                }
            }

            return BeanUtils.instantiateClass(constructorToUse, new Object[0]);
        } else {
            return this.instantiateWithMethodInjection(bd, beanName, owner);
        }
    }
  • 关于doCreateBean方法中的这一段代码:boolean var20 = mbd.isSingleton()……最终影响 var20的最终结果的条件有:

    1.mbd.isSingleton():是否单例。
    2.this.allowCircularReferences:是否允许循环依赖,不能通过配置文件配置,只能通过硬编码的方式设置:

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("knight.xml");
        context.setAllowBeanDefinitionOverriding(false);

    3.this.isSingletonCurrentlyInCreation(beanName):该bean是否在创建中。Spring在创建bean的过程中DefaultSingletonBeanRegistry类型singletonsCurrentlyInCreation来记录bean的加载状态,在bean开始创建前会将beanName记录在属性中,在bean创建结束后会将beanName从属性中移除。

  • 关于doCreateBean方法中的this.addSingletonFactory方法是为了解决单例状态的循环依赖。

//该方法如下,第二个参数是传递一个ObjectFactory的内部类。
this.addSingletonFactory(beanName, new ObjectFactory() {
        public Object getObject() throws BeansException {
               return AbstractAutowireCapableBeanFactory.this.getEarlyBeanReference(beanName, mbd, bean);
        }
});


//追踪ObjectFactory中的getEarlyBeanReference方法源码如下:
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
        Object exposedObject = bean;
        if(bean != null && !mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
            Iterator var5 = this.getBeanPostProcessors().iterator();

            while(var5.hasNext()) {
                BeanPostProcessor bp = (BeanPostProcessor)var5.next();
                if(bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                    SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor)bp;
                    exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
                    if(exposedObject == null) {
                        return null;
                    }
                }
            }
        }

        return exposedObject;
    }

Spring处理循环依赖的流程:
Spring源码解析笔记6——创建bean_第1张图片

总结spring处理循环依赖的办法:在B中创建依赖A时通过ObjectFactory提供的实例化方法来中断A中的属性填充.使B中持有的A仅仅是刚刚初始化并没有填充任何属性的A,而这时初始化A的步骤还是最开始创建A的时候进行的,但是因为A与B中的A所表示的属性地址是一样的,所以A中创建好的属性填充自然也可以通过B中的A获取。

  • this.populateBean(beanName, mbd, instanceWrapper),对bean属性的注入:


//源码如下:
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
        Object pvs = mbd.getPropertyValues();
        if(bw == null) {
            if(!((PropertyValues)pvs).isEmpty()) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
            }
        } else {

            //给hasInstantiationAwareBeanPostProcessors最后一次机会在属性设置前来改变bean。
            //如:可以用来支持属性注入的类型。
            boolean continueWithPropertyPopulation = true;
            if(!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
                Iterator hasInstAwareBpps = this.getBeanPostProcessors().iterator();

                while(hasInstAwareBpps.hasNext()) {
                    BeanPostProcessor needsDepCheck = (BeanPostProcessor)hasInstAwareBpps.next();
                    if(needsDepCheck instanceof InstantiationAwareBeanPostProcessor) {
                        InstantiationAwareBeanPostProcessor filteredPds = (InstantiationAwareBeanPostProcessor)needsDepCheck;

                        //返回值为是否继续填充bean
                        if(!filteredPds.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                            continueWithPropertyPopulation = false;
                            break;
                        }
                    }
                }
            }

            if(continueWithPropertyPopulation) {
                if(mbd.getResolvedAutowireMode() == 1 || mbd.getResolvedAutowireMode() == 2) {
                    MutablePropertyValues hasInstAwareBpps1 = new MutablePropertyValues((PropertyValues)pvs);
                    if(mbd.getResolvedAutowireMode() == 1) {

                        //根据名称自动注入
                        this.autowireByName(beanName, mbd, bw, hasInstAwareBpps1);
                    }

                    if(mbd.getResolvedAutowireMode() == 2) {

                        //根据类型自动注入
                        this.autowireByType(beanName, mbd, bw, hasInstAwareBpps1);
                    }

                    pvs = hasInstAwareBpps1;
                }

                boolean hasInstAwareBpps2 = this.hasInstantiationAwareBeanPostProcessors();
                boolean needsDepCheck1 = mbd.getDependencyCheck() != 0;
                if(hasInstAwareBpps2 || needsDepCheck1) {
                    PropertyDescriptor[] filteredPds1 = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                    if(hasInstAwareBpps2) {
                        Iterator var9 = this.getBeanPostProcessors().iterator();

                        while(var9.hasNext()) {
                            BeanPostProcessor bp = (BeanPostProcessor)var9.next();
                            if(bp instanceof InstantiationAwareBeanPostProcessor) {

                                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp;

                                //对所有需要依赖检查的属性进行后处理。
                                pvs = ibp.postProcessPropertyValues((PropertyValues)pvs, filteredPds1, bw.getWrappedInstance(), beanName);
                                if(pvs == null) {
                                    return;
                                }
                            }
                        }
                    }

                    if(needsDepCheck1) {

                        //依赖检查,对应depends-on属性,3.0以后已经不用了
                        this.checkDependencies(beanName, mbd, filteredPds1, (PropertyValues)pvs);
                    }
                }

                //将属性应用到bean中。
                this.applyPropertyValues(beanName, mbd, bw, (PropertyValues)pvs);
            }
        }
    }

分别讨论一下依赖注入和属性填充:
1.this.autowireByName(beanName, mbd, bw, hasInstAwareBpps1)方法:

 protected void autowireByName(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

        //寻找bw中需要以来的属性。
        String[] propertyNames = this.unsatisfiedNonSimpleProperties(mbd, bw);
        String[] var6 = propertyNames;
        int var7 = propertyNames.length;

        for(int var8 = 0; var8 < var7; ++var8) {
            String propertyName = var6[var8];
            if(this.containsBean(propertyName)) {

                //递归初始化相关的bean
                Object bean = this.getBean(propertyName);
                pvs.add(propertyName, bean);

                //注册依赖
                this.registerDependentBean(propertyName, beanName);
                if(this.logger.isDebugEnabled()) {
                    this.logger.debug("Added autowiring by name from bean name \'" + beanName + "\' via property \'" + propertyName + "\' to bean named \'" + propertyName + "\'");
                }
            } else if(this.logger.isTraceEnabled()) {
                this.logger.trace("Not autowiring property \'" + propertyName + "\' of bean \'" + beanName + "\' by name: no matching bean found");
            }
        }

    }

2.this.autowireByType(beanName, mbd, bw, hasInstAwareBpps1);

protected void autowireByType(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
        Object converter = this.getCustomTypeConverter();
        if(converter == null) {
            converter = bw;
        }

        LinkedHashSet autowiredBeanNames = new LinkedHashSet(4);

        //寻找bw中需要依赖注入的属性。
        String[] propertyNames = this.unsatisfiedNonSimpleProperties(mbd, bw);
        String[] var8 = propertyNames;
        int var9 = propertyNames.length;

        for(int var10 = 0; var10 < var9; ++var10) {
            String propertyName = var8[var10];

            try {
                PropertyDescriptor ex = bw.getPropertyDescriptor(propertyName);
                if(Object.class != ex.getPropertyType()) {

                    //检测指定属性的set方法。
                    MethodParameter methodParam = BeanUtils.getWriteMethodParameter(ex);
                    boolean eager = !PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass());
                    AbstractAutowireCapableBeanFactory.AutowireByTypeDependencyDescriptor desc = new AbstractAutowireCapableBeanFactory.AutowireByTypeDependencyDescriptor(methodParam, eager);

                    //解析指定beanName的属性值,并把解析到的属性名称存储在autowiredBeanNames中,当属性存在多个封装bean时如:
                    //@Autowired private List aList;将会找到所有匹配A类型的bean并将其注入。
                    Object autowiredArgument = this.resolveDependency(desc, beanName, autowiredBeanNames, (TypeConverter)converter);
                    if(autowiredArgument != null) {
                        pvs.add(propertyName, autowiredArgument);
                    }

                    Iterator var17 = autowiredBeanNames.iterator();

                    while(var17.hasNext()) {
                        String autowiredBeanName = (String)var17.next();

                        //注册依赖                    
                        this.registerDependentBean(autowiredBeanName, beanName);
                        if(this.logger.isDebugEnabled()) {
                            this.logger.debug("Autowiring by type from bean name \'" + beanName + "\' via property \'" + propertyName + "\' to bean named \'" + autowiredBeanName + "\'");
                        }
                    }

                    autowiredBeanNames.clear();
                }
            } catch (BeansException var19) {
                throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, var19);
            }
        }

    }


//继续跟踪类型匹配的Object autowiredArgument = this.resolveDependency(desc, beanName, autowiredBeanNames, (TypeConverter)converter);方法:

public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
        descriptor.initParameterNameDiscovery(this.getParameterNameDiscoverer());
        if(javaUtilOptionalClass == descriptor.getDependencyType()) {
            return (new DefaultListableBeanFactory.OptionalDependencyFactory(null)).createOptionalDependency(descriptor, requestingBeanName, new Object[0]);
        } else if(ObjectFactory.class != descriptor.getDependencyType() && ObjectProvider.class != descriptor.getDependencyType()) {
            if(javaxInjectProviderClass == descriptor.getDependencyType()) {

                //ObjectFactory类注入的特殊处理。
                return (new DefaultListableBeanFactory.Jsr330ProviderFactory(null)).createDependencyProvider(descriptor, requestingBeanName);
            } else {
                Object result = this.getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(descriptor, requestingBeanName);
                if(result == null) {

                    //通用的逻辑处理
                    result = this.doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
                }

                return result;
            }
        } else {
            return new DefaultListableBeanFactory.DependencyObjectProvider(descriptor, requestingBeanName);
        }
    }

//继续跟踪doResolveDependency方法。
public Object doResolveDependency(DependencyDescriptor descriptor, String beanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
        InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);

        Object entry;
        try {
            Object shortcut = descriptor.resolveShortcut(this);
            if(shortcut != null) {
                Object type1 = shortcut;
                return type1;
            }

            Class type = descriptor.getDependencyType();

            //用于支持spring中新增的注解@Value
            Object value = this.getAutowireCandidateResolver().getSuggestedValue(descriptor);
            Object matchingBeans1;
            if(value != null) {
                if(value instanceof String) {
                    String multipleBeans1 = this.resolveEmbeddedValue((String)value);
                    BeanDefinition matchingBeans2 = beanName != null && this.containsBean(beanName)?this.getMergedBeanDefinition(beanName):null;
                    value = this.evaluateBeanDefinitionString(multipleBeans1, matchingBeans2);
                }

                TypeConverter multipleBeans2 = typeConverter != null?typeConverter:this.getTypeConverter();
                matchingBeans1 = descriptor.getField() != null?multipleBeans2.convertIfNecessary(value, type, descriptor.getField()):multipleBeans2.convertIfNecessary(value, type, descriptor.getMethodParameter());
                return matchingBeans1;
            }

            Object multipleBeans = this.resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
            if(multipleBeans != null) {
                matchingBeans1 = multipleBeans;
                return matchingBeans1;
            }

            Map matchingBeans = this.findAutowireCandidates(beanName, type, descriptor);
            String autowiredBeanName;
            if(matchingBeans.isEmpty()) {
                if(descriptor.isRequired()) {
                    this.raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
                }

                autowiredBeanName = null;
                return autowiredBeanName;
            }

            Object instanceCandidate;
            if(matchingBeans.size() > 1) {
                autowiredBeanName = this.determineAutowireCandidate(matchingBeans, descriptor);
                if(autowiredBeanName == null) {
                    if(descriptor.isRequired() || !this.indicatesMultipleBeans(type)) {
                        entry = descriptor.resolveNotUnique(type, matchingBeans);
                        return entry;
                    }

                    entry = null;
                    return entry;
                }

                instanceCandidate = matchingBeans.get(autowiredBeanName);
            } else {
                Entry entry1 = (Entry)matchingBeans.entrySet().iterator().next();
                autowiredBeanName = (String)entry1.getKey();
                instanceCandidate = entry1.getValue();
            }

            if(autowiredBeanNames != null) {
                autowiredBeanNames.add(autowiredBeanName);
            }

            entry = instanceCandidate instanceof Class?descriptor.resolveCandidate(autowiredBeanName, type, this):instanceCandidate;
        } finally {
            ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
        }

        return entry;
    }

3.程序经过前两步是已经完成了注入属性的获取,但是获取到的属性是以PropertyValue形式存在的,还并没有应用到已经实例化的bean中,这一工作是由this.applyPropertyValues(beanName, mbd, bw, (PropertyValues)pvs)去实现的。

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
        if(pvs != null && !pvs.isEmpty()) {
            MutablePropertyValues mpvs = null;
            if(System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
                ((BeanWrapperImpl)bw).setSecurityContext(this.getAccessControlContext());
            }

            List original;
            if(pvs instanceof MutablePropertyValues) {
                mpvs = (MutablePropertyValues)pvs;

                //如果mpvs中的值已经被转换为对应的类型那么可以直接设置到beanwapper中。
                if(mpvs.isConverted()) {
                    try {
                        bw.setPropertyValues(mpvs);
                        return;
                    } catch (BeansException var18) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Error setting property values", var18);
                    }
                }

                original = mpvs.getPropertyValueList();
            } else {

                //如果pvs并不是使用MutablePropertyValues封装的类型,那么直接使用原始的属性获取方法。
                original = Arrays.asList(pvs.getPropertyValues());
            }

            Object converter = this.getCustomTypeConverter();
            if(converter == null) {
                converter = bw;
            }

            //获取对应的解析器。
            BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, (TypeConverter)converter);
            ArrayList deepCopy = new ArrayList(original.size());
            boolean resolveNecessary = false;
            Iterator ex = original.iterator();

            //遍历属性,将属性转换为对应类的对应属性的类型。
            while(true) {
                while(ex.hasNext()) {
                    PropertyValue pv = (PropertyValue)ex.next();
                    if(pv.isConverted()) {
                        deepCopy.add(pv);
                    } else {
                        String propertyName = pv.getName();
                        Object originalValue = pv.getValue();
                        Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
                        Object convertedValue = resolvedValue;
                        boolean convertible = bw.isWritableProperty(propertyName) && !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
                        if(convertible) {
                            convertedValue = this.convertForProperty(resolvedValue, propertyName, bw, (TypeConverter)converter);
                        }

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

                try {
                    bw.setPropertyValues(new MutablePropertyValues(deepCopy));
                    return;
                } catch (BeansException var19) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Error setting property values", var19);
                }
            }
        }
    }

你可能感兴趣的:(Spring)