通过构造方法创建Bean实例(推断构造方法)

1.代码入口AbstractAutowireCapableBeanFactory#createBeanInstance

    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
        // Make sure bean class is actually resolved at this point.
        //返回mbd中真实bean的Class对象。
        Class beanClass = resolveBeanClass(mbd, beanName);

        //三个条件想表达的意思:bd中如果nonPublicAccessAllowed字段值为true,表示class是非公开类型的 也可以创建实例,反之false,说明是无法创建的..
        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());
        }

        // InstanceSupplier
        Supplier instanceSupplier = mbd.getInstanceSupplier();
        if (instanceSupplier != null) {
            return obtainFromSupplier(instanceSupplier, beanName);
        }

        //bean标签中配置了 factory-method的情况处理
        // bd中提供了factoryMethodName属性,那么要使用工厂方法的方式来创建对象,
        // 工厂方法又会区分静态工厂方法跟实例工厂方法
        if (mbd.getFactoryMethodName() != null) {
            return instantiateUsingFactoryMethod(beanName, mbd, args);
        }

        // Shortcut when re-creating the same bean...
        //表示bd对应的构造信息是否已经解析成可以反射调用的构造方法method信息了
        // 是否推断过构造方法
        boolean resolved = false;
        //是否自动匹配构造方法,构造方法是否需要注入(参数)
        boolean autowireNecessary = false;
        if (args == null) {
            synchronized (mbd.constructorArgumentLock) {
                //条件成立:说明bd的构造信息已经转化成可以反射调用的method了
                if (mbd.resolvedConstructorOrFactoryMethod != null) {
                    resolved = true;
                    //当resolvedConstructorOrFactoryMethod 有值时,且构造方法有参数,那么可以认为这个字段值就是true。
                    //只有什么情况下这个字段是false呢?
                    //1.resolvedConstructorOrFactoryMethod == null
                    //2.当resolvedConstructorOrFactoryMethod 表示的是默认的构造方法,无参构造方法。
                    autowireNecessary = mbd.constructorArgumentsResolved;
                }
            }
        }
        if (resolved) {
            // 构造函数已经解析过了,并且这个构造函数在调用时需要自动注入参数
            if (autowireNecessary) {
                //有参数,那么就需要根据参数 去匹配合适的构造方法了...
                //拿出当前Class的所有构造器,然后根据参数信息 去匹配出一个最优的选项,然后执行最优的 构造器 创建出实例。
                // 此时部分解析好的参数已经存在了beanDefinition中,并且构造函数也在bd中
                // 那么在这里只会从缓存中去取构造函数以及参数然后反射调用
                return autowireConstructor(beanName, mbd, null, null);
            }
            else {
                //无参构造方法处理
                return instantiateBean(beanName, mbd);
            }
        }

        // Candidate constructors for autowiring?
        //  典型的应用:@Autowired 注解打在了 构造器方法上。参考@Autowired AutowiredAnnotationBeanPostProcessor
        Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
        //条件一:ctors不为null:说明存在1个或多个@Autowired标注的方法。
        // 再进一步选择一个差异值最小的,参数最长的构造函数
        //条件二:mbd autowiredMode 一般情况是no
        // 没有@Autowired标注的方法,但是需要进行自动注入,
        // 那么通过autowireConstructor会去遍历类中申明的所有构造函数,
        // 并查找一个差异值最小的,参数最长的构造函数
        //条件三:条件成立,说明bean信息中配置了 构造参数信息。
        // 说明不是自动注入,配置文件中配置了构造函数要使用的参数
        //条件四:getBean时,args有参数
        if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
                mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
            return autowireConstructor(beanName, mbd, ctors, args);
        }

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

        // No special handling: simply use no-arg constructor.
        //未指定构造参数,未设定偏好...使用默认的 无参数的构造方法进行创建实例。
        return instantiateBean(beanName, mbd);
    }

调用无参构造方法:

        //未指定构造参数,未设定偏好...使用默认的 无参数的构造方法进行创建实例。
        // No special handling: simply use no-arg constructor.
        return instantiateBean(beanName, mbd);

autowireConstructor()调用:

    protected BeanWrapper autowireConstructor(
            String beanName, RootBeanDefinition mbd, @Nullable Constructor[] ctors, @Nullable Object[] explicitArgs) {

        return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
    }

2.ConstructorResolver#autowireConstructor

参考通过factory-method创建Bean实例:https://www.jianshu.com/p/c9ab0026be34
跟ConstructorResolver#instantiateUsingFactoryMethod流程一模一样

    public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
            @Nullable Constructor[] chosenCtors, @Nullable Object[] explicitArgs) {

        BeanWrapperImpl bw = new BeanWrapperImpl();
        //1.向wrapper中注册 ConversionService
        //2.向wrapper中注册 属性编辑器..
        this.beanFactory.initBeanWrapper(bw);

        //实例化反射调用的构造器
        Constructor constructorToUse = null;
        //实例化时真正去用的参数 持有对象。
        ArgumentsHolder argsHolderToUse = null;
        //实例化时使用的参数。
        Object[] argsToUse = null;

        if (explicitArgs != null) {
            argsToUse = explicitArgs;
        }
        else {
            //表示 构造器参数需要做转换的参数引用。
            Object[] argsToResolve = null;
            synchronized (mbd.constructorArgumentLock) {
                constructorToUse = (Constructor) mbd.resolvedConstructorOrFactoryMethod;
                //条件成立:说明当前bd生成实例,不是第一次..缓存中有解析好的构造器方法可以直接拿来反射调用...
                //constructorArgumentsResolved 条件成立,说明构造器参数已经解析过了..
                if (constructorToUse != null && mbd.constructorArgumentsResolved) {
                    // Found a cached constructor...
                    argsToUse = mbd.resolvedConstructorArguments;
                    if (argsToUse == null) {
                        argsToResolve = mbd.preparedConstructorArguments;
                    }
                }
            }
            //条件成立:resolvedConstructorArguments 参数是null,那preparedConstructorArguments一定是有值的。
            if (argsToResolve != null) {
                //可以认为preparedConstructorArguments 不是完全解析好的参数..还需要进一步解析。。。
                argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve, true);
            }
        }

        //条件成立:说明上面缓存机制失败,需要进行构造器匹配逻辑...autowireConstructors
        if (constructorToUse == null || argsToUse == null) {
            // Take specified constructors, if any.
            //chosenCtors 什么时候有数据呢? 构造方法上有@Autowired注解时,chosenCtors才会有数据。
            Constructor[] candidates = chosenCtors;
            // 条件成立:说明外部程序调用当前autowireConstructors方法时,并没有提供好 可选用的构造器..
            // 咱们需要通过Class拿到构造器信息
            if (candidates == null) {
                Class beanClass = mbd.getBeanClass();
                try {
                    //isNonPublicAccessAllowed 返回true,表示当前bd中的Class非public的方法也可以访问..
                    // beanClass.getDeclaredConstructors()获取所有构造方法
                    // beanClass.getConstructors() 获取public的构造方法
                    candidates = (mbd.isNonPublicAccessAllowed() ?
                            beanClass.getDeclaredConstructors() : beanClass.getConstructors());
                }
                catch (Throwable ex) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                            "Resolution of declared constructors on bean Class [" + beanClass.getName() +
                            "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
                }
            }
            //执行到这里,可选用的构造方法,已经准备好了..具体使用哪一个 还不清楚..

            //条件成立:说明当前实例化 想要使用无参构造方法!
            if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
                Constructor uniqueCandidate = candidates[0];
                //条件成立:说明当前这个唯一可选项 构造器 就是 无参构造器!
                if (uniqueCandidate.getParameterCount() == 0) {
                    synchronized (mbd.constructorArgumentLock) {
                        mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
                        mbd.constructorArgumentsResolved = true;
                        mbd.resolvedConstructorArguments = EMPTY_ARGS;
                    }
                    //instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS) 使用无参构造器 完成反射调用,
                    // 创建出来实例对象。
                    bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
                    return bw;
                }
            }

            // Need to resolve the constructor.
            boolean autowiring = (chosenCtors != null ||
                    mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
            //表示已经完成解析后的构造器参数值
            ConstructorArgumentValues resolvedValues = null;
            //表示构造器参数个数..
            int minNrOfArgs;
            if (explicitArgs != null) {
                minNrOfArgs = explicitArgs.length;
            }
            else {
                ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
                //表示已经完成解析后的构造器参数值
                resolvedValues = new ConstructorArgumentValues();
                //表示构造器参数个数..
                minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
            }

            //给可选用的构造器数组排序
            //排序规则:public > 非公开 > 参数多的 > 参数少的
            AutowireUtils.sortConstructors(candidates);
            //这是什么?
            //这个值越低,说明当前构造器参数列表类型和构造器参数匹配度越高,反之,这个值越高,
            // 说明当前构造器参数列表类型和构造器参数匹配度越低..
            int minTypeDiffWeight = Integer.MAX_VALUE;
            //模棱两可的构造器? 假设第二个构造器的diffWeight值 与上一个一致,则将其放入到该集合..
            Set> ambiguousConstructors = null;
            LinkedList causes = null;

            //筛选可选项 构造方法,找出一个diffWeight最低的构造器
            for (Constructor candidate : candidates) {
                //获取当前处理的构造器参数个数..
                int parameterCount = candidate.getParameterCount();

                //constructorToUse != null && argsToUse != null && argsToUse.length 
                // 这些参数的数据,都上前面循环筛选出来的东西..
                //因为candidates是排过顺序的 排序规则:public > 非公开 > 参数多的 > 参数少的
                //当前筛选出来的构造器 优先级 一定是优先于后面的 Constructor的。
                if (constructorToUse != null && argsToUse != null && argsToUse.length > parameterCount) {
                    // Already found greedy constructor that can be satisfied ->
                    // do not look any further, there are only less greedy constructors left.
                    break;
                }
                //minNrOfArgs表示bd中配置的构造器参数个数
                //parameterCount 表示当前构造器参数个数
                //条件成立:说明不匹配..
                if (parameterCount < minNrOfArgs) {
                    continue;
                }

                ArgumentsHolder argsHolder;
                //获取当前构造器参数类型数组..
                Class[] paramTypes = candidate.getParameterTypes();
                //条件成立:说明bd中配置了构造器参数
                if (resolvedValues != null) {
                    try {
                        //@ConstructorProperties(value=["a","b"])
                        //Student(String name, String sex)
                        // 给参数重新设置了名字
                        String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, parameterCount);
                        if (paramNames == null) {
                            ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                            if (pnd != null) {
                                //Student(String name, String sex)  ==>  ["name", "sex"]
                                // 就是默认的名字
                                paramNames = pnd.getParameterNames(candidate);
                            }
                        }
                        argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
                                getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
                    }
                    catch (UnsatisfiedDependencyException ex) {
                        if (logger.isTraceEnabled()) {
                            logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
                        }
                        // Swallow and try next constructor.
                        if (causes == null) {
                            causes = new LinkedList<>();
                        }
                        causes.add(ex);
                        continue;
                    }
                }
                else {
                    // Explicit arguments given -> arguments length must match exactly.
                    if (parameterCount != explicitArgs.length) {
                        continue;
                    }
                    argsHolder = new ArgumentsHolder(explicitArgs);
                }

                //LenientConstructorResolution == true 表示 ambiguousConstructors 允许有数据
                //LenientConstructorResolution == false 表示 ambiguousConstructors 不允许有数据,有数据的话 会报错..

                //typeDiffWeight 数值越高说明构造器与参数匹配度越低...
                //计算出当前构造器参数类型 与 当前 构造器参数 匹配度。
                int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
                        argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
                // Choose this constructor if it represents the closest match.
                //条件成立:说明当前循环处理的 构造器 比上一次筛选出来的构造器 更优先。
                if (typeDiffWeight < minTypeDiffWeight) {
                    constructorToUse = candidate;
                    argsHolderToUse = argsHolder;
                    argsToUse = argsHolder.arguments;
                    minTypeDiffWeight = typeDiffWeight;
                    ambiguousConstructors = null;
                }
                //条件成立:说明当前处理的构造器 它计算出来的diffWeight值 与上一次 
                // 筛选出来的最优先的构造器的值一致...说明有模棱两可的情况...
                else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
                    if (ambiguousConstructors == null) {
                        ambiguousConstructors = new LinkedHashSet<>();
                        ambiguousConstructors.add(constructorToUse);
                    }
                    ambiguousConstructors.add(candidate);
                }
            }

            //条件成立:说明未找到可以使用的构造器...只能报错了...
            if (constructorToUse == null) {
                if (causes != null) {
                    UnsatisfiedDependencyException ex = causes.removeLast();
                    for (Exception cause : causes) {
                        this.beanFactory.onSuppressedException(cause);
                    }
                    throw ex;
                }
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Could not resolve matching constructor " +
                        "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
            }
            //LenientConstructorResolution == false 表示 ambiguousConstructors 不允许有数据,
            // 有数据的话 会报错..
            else 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);
            }

            //条件成立:说明自动匹配成功了..需要进行缓存。方便后来者...再次使用该bd实例化..
            if (explicitArgs == null && argsHolderToUse != null) {
                argsHolderToUse.storeCache(mbd, constructorToUse);
            }
        }

        Assert.state(argsToUse != null, "Unresolved constructor arguments");
        bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
        return bw;
    }

3.解析参数ConstructorResolver#resolveConstructorArguments

    private int resolveConstructorArguments(String beanName, RootBeanDefinition mbd, BeanWrapper bw,
            ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) {

        TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
        TypeConverter converter = (customConverter != null ? customConverter : bw);
        BeanDefinitionValueResolver valueResolver =
                new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);

        int minNrOfArgs = cargs.getArgumentCount();

        for (Map.Entry entry : cargs.getIndexedArgumentValues().entrySet()) {
            int index = entry.getKey();
            if (index < 0) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Invalid constructor argument index: " + index);
            }
            if (index + 1 > minNrOfArgs) {
                minNrOfArgs = index + 1;
            }
            ConstructorArgumentValues.ValueHolder valueHolder = entry.getValue();
            if (valueHolder.isConverted()) {
                resolvedValues.addIndexedArgumentValue(index, valueHolder);
            }
            else {
                Object resolvedValue =
                        valueResolver.resolveValueIfNecessary("constructor argument", valueHolder.getValue());
                ConstructorArgumentValues.ValueHolder resolvedValueHolder =
                        new ConstructorArgumentValues.ValueHolder(resolvedValue, valueHolder.getType(), valueHolder.getName());
                resolvedValueHolder.setSource(valueHolder);
                resolvedValues.addIndexedArgumentValue(index, resolvedValueHolder);
            }
        }

        for (ConstructorArgumentValues.ValueHolder valueHolder : cargs.getGenericArgumentValues()) {
            if (valueHolder.isConverted()) {
                resolvedValues.addGenericArgumentValue(valueHolder);
            }
            else {
                Object resolvedValue =
                        valueResolver.resolveValueIfNecessary("constructor argument", valueHolder.getValue());
                ConstructorArgumentValues.ValueHolder resolvedValueHolder = new ConstructorArgumentValues.ValueHolder(
                        resolvedValue, valueHolder.getType(), valueHolder.getName());
                resolvedValueHolder.setSource(valueHolder);
                resolvedValues.addGenericArgumentValue(resolvedValueHolder);
            }
        }

        return minNrOfArgs;
    }

解析方法BeanDefinitionValueResolver#resolveValueIfNecessary:

    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);
        }
        else if (value instanceof RuntimeBeanNameReference) {
            String refName = ((RuntimeBeanNameReference) value).getBeanName();
            refName = String.valueOf(doEvaluate(refName));
            if (!this.beanFactory.containsBean(refName)) {
                throw new BeanDefinitionStoreException(
                        "Invalid bean name '" + refName + "' in bean reference for " + argName);
            }
            return refName;
        }
        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);
        }
...

这里会去解析参数bean,一般调用getBean()

    private Object resolveReference(Object argName, RuntimeBeanReference ref) {
        try {
            Object bean;
            Class beanType = ref.getBeanType();
            if (ref.isToParent()) {
                BeanFactory parent = this.beanFactory.getParentBeanFactory();
                if (parent == null) {
                    throw new BeanCreationException(
                            this.beanDefinition.getResourceDescription(), this.beanName,
                            "Cannot resolve reference to bean " + ref +
                                    " in parent factory: no parent factory available");
                }
                if (beanType != null) {
                    bean = parent.getBean(beanType);
                }
                else {
                    bean = parent.getBean(String.valueOf(doEvaluate(ref.getBeanName())));
                }
            }
            else {
                String resolvedName;
                if (beanType != null) {
                    NamedBeanHolder namedBean = this.beanFactory.resolveNamedBean(beanType);
                    bean = namedBean.getBeanInstance();
                    resolvedName = namedBean.getBeanName();
                }
                else {
                    resolvedName = String.valueOf(doEvaluate(ref.getBeanName()));
                    bean = this.beanFactory.getBean(resolvedName);
                }
                this.beanFactory.registerDependentBean(resolvedName, 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);
        }
    }

4.AutowiredAnnotationBeanPostProcessor#determineCandidateConstructors

查找到被@Autowired注解标注的构造函数

  • 如果存在多个被@Autowired标注的构造函数,并且其required属性没有被设置为true,那么返回这些被标注的函数的集合(空参构造即使没有添加@Autowired也会被添加到集合中)
  • 如果存在多个被@Autowired标注的构造函数,并且其中一个的required属性被设置成了true,那么直接报错
  • 如果只有一个构造函数被@Autowired标注,并且其required属性被设置成了true,那么直接返回这个构造函数
  • 如果没有被@Autowired标注标注的构造函数,但是类中有且只有一个构造函数,并且这个构造函数不是空参构造函数,那么返回这个构造函数
  • 上面的条件都不满足,那么determineCandidateConstructors这个方法就无法推断出合适的构造函数了
    // 这个方法看起来很长,但实际确很简单,就是通过@Autowired注解确定哪些构造方法可以作为候选方法,
    // 其实在使用factoryMethod来实例化对象的时候也有这种逻辑在其中
    public Constructor[] determineCandidateConstructors(Class beanClass, final String beanName)
            throws BeanCreationException {

        // Let's check for lookup methods here...
        // 这里做的事情很简单,就是将@Lookup注解标注的方法封装成LookupOverride添加
        // 到BeanDefinition中的methodOverrides属性中,如果这个属性不为空,
        // 在实例化对象的时候不能选用SimpleInstantiationStrategy,
        // 而要使用CglibSubclassingInstantiationStrategy,
        // 通过cglib代理给方法加一层拦截了逻辑
        // 避免重复检查
        if (!this.lookupMethodsChecked.contains(beanName)) {
            if (AnnotationUtils.isCandidateClass(beanClass, Lookup.class)) {
                try {
                    Class targetClass = beanClass;
                    do {
                        ReflectionUtils.doWithLocalMethods(targetClass, method -> {
                            Lookup lookup = method.getAnnotation(Lookup.class);
                            if (lookup != null) {
                                Assert.state(this.beanFactory != null, "No BeanFactory available");
                                LookupOverride override = new LookupOverride(method, lookup.value());
                                try {
                                    // 添加到BeanDefinition中的methodOverrides属性中
                                    RootBeanDefinition mbd = (RootBeanDefinition)
                                            this.beanFactory.getMergedBeanDefinition(beanName);
                                    mbd.getMethodOverrides().addOverride(override);
                                }
                                catch (NoSuchBeanDefinitionException ex) {
                                    throw new BeanCreationException(beanName,
                                            "Cannot apply @Lookup to beans without corresponding bean definition");
                                }
                            }
                        });
                        targetClass = targetClass.getSuperclass();
                    }
                    while (targetClass != null && targetClass != Object.class);

                }
                catch (IllegalStateException ex) {
                    throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
                }
            }
            this.lookupMethodsChecked.add(beanName);
        }

        // Quick check on the concurrent map first, with minimal locking.
        // 接下来要开始确定到底哪些构造函数能被作为候选者
        // 先尝试从缓存中获取
        Constructor[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
        if (candidateConstructors == null) {
            // Fully synchronized resolution now...
            synchronized (this.candidateConstructorsCache) {
                candidateConstructors = this.candidateConstructorsCache.get(beanClass);
                if (candidateConstructors == null) {
                    Constructor[] rawCandidates;
                    try {
                        // 第一步:先查询这个类所有的构造函数,包括私有的
                        rawCandidates = beanClass.getDeclaredConstructors();
                    }
                    catch (Throwable ex) {
                        throw new BeanCreationException(beanName,
                                "Resolution of declared constructors on bean Class [" + beanClass.getName() +
                                "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
                    }
                    List> candidates = new ArrayList<>(rawCandidates.length);
                    //唯一的选项 构造器 ,什么情况下,这个变量有值呢?
                    //@Autowired(required = "true")
                    // 保存添加了Autowired注解并且required属性为true的构造方法
                    Constructor requiredConstructor = null;
                    //缺省的 构造器,无参构造器
                    Constructor defaultConstructor = null;
                    Constructor primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
                    int nonSyntheticConstructors = 0;
                    for (Constructor candidate : rawCandidates) {
                        if (!candidate.isSynthetic()) {
                            nonSyntheticConstructors++;
                        }
                        else if (primaryConstructor != null) {
                            continue;
                        }
                        //如果构造方法上 有@Autowired 或者 @Value 或者 @Inject 这里ann就不为null。
                        MergedAnnotation ann = findAutowiredAnnotation(candidate);
                        if (ann == null) {
                            Class userClass = ClassUtils.getUserClass(beanClass);
                            // userClass != beanClass说明这个类进行了cglib代理
                            if (userClass != beanClass) {
                                try {
                                    // 如果进行了cglib代理,那么在父类上再次查找Autowired注解
                                    Constructor superCtor =
                                            userClass.getDeclaredConstructor(candidate.getParameterTypes());
                                    ann = findAutowiredAnnotation(superCtor);
                                }
                                catch (NoSuchMethodException ex) {
                                    // Simply proceed, no equivalent superclass constructor found...
                                }
                            }
                        }
                        // 说明当前的这个构造函数上有Autowired注解
                        if (ann != null) {
                            if (requiredConstructor != null) {
                                throw new BeanCreationException(beanName,
                                        "Invalid autowire-marked constructor: " + candidate +
                                        ". Found constructor with 'required' Autowired annotation already: " +
                                        requiredConstructor);
                            }
                            // 获取Autowired注解中的required属性
                            boolean required = determineRequiredStatus(ann);
                            if (required) {
                                //@Autowired(require = true) 有这种注解的Class,
                                // 就只能有一个构造方法可用。如果
                                // 其它的构造方法上 还有 @Autowired 那报错。
                                if (!candidates.isEmpty()) {
                                    throw new BeanCreationException(beanName,
                                            "Invalid autowire-marked constructors: " + candidates +
                                            ". Found constructor with 'required' Autowired annotation: " +
                                            candidate);
                                }
                                requiredConstructor = candidate;
                            }
                            // 添加到集合中,这个集合存储的都是被@Autowired注解标注的方法
                            candidates.add(candidate);
                        }
                        //条件成立:说明当前遍历的构造器 就是 默认无参构造器
                        else if (candidate.getParameterCount() == 0) {
                            defaultConstructor = candidate;
                        }
                    }
                    if (!candidates.isEmpty()) {
                        // Add default constructor to list of optional constructors, as fallback.
                        // 存在多个被@Autowired标注的方法
                        // 并且所有的required属性被设置成了false (默认为true)
                        if (requiredConstructor == null) {
                            // 存在空参构造函数,注意,空参构造函数可以不被@Autowired注解标注
                            if (defaultConstructor != null) {
                                // 将空参构造函数也加入到候选的方法中去
                                candidates.add(defaultConstructor);
                            }
                            else if (candidates.size() == 1 && logger.isInfoEnabled()) {
                                logger.info("Inconsistent constructor declaration on bean with name '" + beanName +
                                        "': single autowire-marked constructor flagged as optional - " +
                                        "this constructor is effectively required since there is no " +
                                        "default constructor to fall back to: " + candidates.get(0));
                            }
                        }
                        candidateConstructors = candidates.toArray(new Constructor[0]);
                    }
                    // 也就是说,类中只提供了一个构造函数,并且这个构造函数不是空参构造函数
                    else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
                        candidateConstructors = new Constructor[] {rawCandidates[0]};
                    }
                    else if (nonSyntheticConstructors == 2 && primaryConstructor != null &&
                            defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
                        candidateConstructors = new Constructor[] {primaryConstructor, defaultConstructor};
                    }
                    else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
                        candidateConstructors = new Constructor[] {primaryConstructor};
                    }
                    else {
                        // 说明无法推断出来
                        candidateConstructors = new Constructor[0];
                    }
                    this.candidateConstructorsCache.put(beanClass, candidateConstructors);
                }
            }
        }
        return (candidateConstructors.length > 0 ? candidateConstructors : null);
    }

你可能感兴趣的:(通过构造方法创建Bean实例(推断构造方法))