创建bean的流程三


### -----------------------doCreateBean------------------bean实例化

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

        // Instantiate the bean.
        createBeanInstance()

        // Allow post-processors to modify the merged bean definition.
        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);           合并bean定义后的处理:如@Autowird标记再属性上,就在这里解析,仅解析
                }
                catch (Throwable ex) {
                    throw new BeanCreationException();
                }
                mbd.markAsPostProcessed();
            }
        }

        boolean earlySingletonExposure = (mbd.isSingleton() && // 单例
                                  this.allowCircularReferences && // 允许循环依赖
                                  isSingletonCurrentlyInCreation(beanName)); // 正在创建的单例
        if (earlySingletonExposure) {
            
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        }

        // Initialize the bean instance.
        populateBean(beanName, mbd, instanceWrapper);
        exposedObject = initializeBean(beanName, exposedObject, mb

        if (earlySingletonExposure) {
            Object earlySingletonReference = getSingleton(beanName, false);
            if (earlySingletonReference != null) {
                if (exposedObject == bean) {
                    exposedObject = earlySingletonReference;
                }
                else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                    String[] dependentBeans = getDependentBeans(beanName);
                    Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                    for (String dependentBean : dependentBeans) {
                        if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                            actualDependentBeans.add(dependentBean);
                        }
                    }
                    if (!actualDependentBeans.isEmpty()) {
                        throw new BeanCurrentlyInCreationException( );
                    }
                }
            }
        }

        // Register bean as disposable.
        registerDisposableBeanIfNecessary(beanName, bean, mbd)
    }

-> AbstractAutowireCapableBeanFactory.createBeanInstance()                      主要负责创建bean的相关方法有两个,
                                                                                分别是autowireConstructor(...)和instantiateBean(...)                            

    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
        /** 步骤1:解析beanClass */
        Class<?> beanClass = resolveBeanClass(mbd, beanName);
        if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) 
            throw new BeanCreationException(...);

        /** 步骤2:如果配置了instanceSupplier,则通过调用Supplier#get()方法来创建bean的实例,并封装为BeanWrapper实例 */
        Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
        if (instanceSupplier != null) return obtainFromSupplier(instanceSupplier, beanName);

        /** 步骤3:如果配置了factoryMethodName或者配置文件中存在factory-method,则使用工厂方法创建bean的实例 */
        if (mbd.getFactoryMethodName() != null) return instantiateUsingFactoryMethod(beanName, mbd, args);

        boolean resolved = false, autowireNecessary = false;
        if (args == null) {
            synchronized (mbd.constructorArgumentLock) {
                // 一个类有多个构造函数,每个构造函数有不同的参数,所以调用前需要先根据参数锁定构造函数或者对应的工厂方法
                if (mbd.resolvedConstructorOrFactoryMethod != null) {
                    resolved = true;
                    autowireNecessary = mbd.constructorArgumentsResolved;
                }
            }
        }

        /** 步骤4:如果已经解析过(resolved=true),那么就使用解析好的构造函数方法,不需要再次锁定 */
        if (resolved) {
            if (autowireNecessary) 
                return autowireConstructor(beanName, mbd, null, null);                                                  构造函数自动注入
            else 
                return instantiateBean(beanName, mbd);                                                                  使用默认构造函数构造
        }

        /** 步骤5:如果没解析过,那么则需要根据参数解析构造函数 */
        Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
        if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
                mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
            return autowireConstructor(beanName, mbd, ctors, args);                                                     构造函数自动注入
        }

        /** 步骤6:尝试获取默认构造的首选构造函数 */
        ctors = mbd.getPreferredConstructors();
        if (ctors != null) return autowireConstructor(beanName, mbd, ctors, null);                                      构造函数自动注入

        /** 步骤7:如果以上都不行,则使用默认构造函数构造bean实例 */
        return instantiateBean(beanName, mbd); 
    }

    autowireConstructor(...)有参数的实例化构造
    
        public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd, Constructor<?>[] chosenCtors, 
                                               Object[] explicitArgs) {
            BeanWrapperImpl bw = new BeanWrapperImpl();
            this.beanFactory.initBeanWrapper(bw);
            Constructor<?> constructorToUse = null;
            ArgumentsHolder argsHolderToUse = null;
            
            /** 步骤1:尝试获得构造函数(constructorToUse)和方法入参(argsToUse)*/
            Object[] argsToUse = null;
            if (explicitArgs != null) // case1:如果getBean方法调用的时候指定了方法参数,则直接使用
                argsToUse = explicitArgs; 
            else { // case2:如果没有指定explicitArgs,则尝试从mbd中获取构造函数入参argsToUse和构造函数constructorToUse
                Object[] argsToResolve = null;
                synchronized (mbd.constructorArgumentLock) {
                    constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
                    if (constructorToUse != null && mbd.constructorArgumentsResolved) {
                        argsToUse = mbd.resolvedConstructorArguments;
                        if (argsToUse == null) argsToResolve = mbd.preparedConstructorArguments;
                    }
                }
                if (argsToResolve != null) 
                    // 转换参数类型。假设构造函数为A(int, int),可以通过如下方法将入参的("1", "1")转换为(1, 1)
                    argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
            }

            /** 步骤2:如果constructorToUse和argsToUse没有全部解析出来,则尝试从配置文件中解析获取 */
            if (constructorToUse == null || argsToUse == null) {
                Constructor<?>[] candidates = chosenCtors; 
                if (candidates == null) { // 如果入参chosenCtors为空,则获取bean中所有的构造方法作为“候选”构造方法
                    Class<?> beanClass = mbd.getBeanClass();
                    try {
                        candidates = (mbd.isNonPublicAccessAllowed() ? 
                                      beanClass.getDeclaredConstructors() : 
                                      beanClass.getConstructors());
                    } catch (Throwable ex) {...}
                }
                
                // 如果类中只有1个无参的构造函数,则创建bean的实例对象并且return
                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;
                        }
                        bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
                        return bw;
                    }
                }

                boolean autowiring = (chosenCtors != null || 
                                      mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
                ConstructorArgumentValues resolvedValues = null;
                // 解析构造函数参数个数minNrOfArgs
                int minNrOfArgs;
                if (explicitArgs != null) minNrOfArgs = explicitArgs.length;
                else {
                    ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues(); // 提取配置文件中配置的构造函数参数
                    resolvedValues = new ConstructorArgumentValues(); // 用于承载解析后的构造函数参数的值
                    minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues); // 解析参数个数
                }
                
                // 对构造函数执行排序操作,其中:public构造函数优先且参数数量降序排列,然后是非public构造函数参数数量降序排列
                AutowireUtils.sortConstructors(candidates); 

                // 遍历所有构造函数,对每个构造函数进行参数匹配操作
                int minTypeDiffWeight = Integer.MAX_VALUE;
                Set<Constructor< ?>> ambiguousConstructors = null;
                Deque<UnsatisfiedDependencyException> causes = null;
                for (Constructor< ?> candidate : candidates) {
                    int parameterCount = candidate.getParameterCount();
                    if (constructorToUse != null && argsToUse != null && argsToUse.length > parameterCount) break;
                    if (parameterCount < minNrOfArgs) continue; 

                    /** 创建构造函数的”参数持有者(ArgumentsHolder)“实例对象argsHolder */
                    ArgumentsHolder argsHolder;
                    Class<?>[] paramTypes = candidate.getParameterTypes(); // 获得构造函数的参数类型集合
                    if (resolvedValues != null) { // 只有当explicitArgs等于null时,resolvedValues才满足不为空
                        try {
                            // 获得@ConstructorProperties({"x", "y"})注解里配置的参数名称
                            String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, parameterCount);
                            if (paramNames == null) {
                                // 从BeanFactory中获得配置的ParameterNameDiscoverer实现类
                                ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                                if (pnd != null) 
                                    paramNames = pnd.getParameterNames(candidate); // 获得构造函数的参数名称
                            }
                            // 根据【paramTypes】和【paramNames】创建参数持有者ArgumentsHolder
                            argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
                                    getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
                        } catch (UnsatisfiedDependencyException ex) {...}
                    } else {
                        if (parameterCount != explicitArgs.length) continue;
                        argsHolder = new ArgumentsHolder(explicitArgs);
                    }

                    /** 探测是否有不确定性的构造函数存在,例如:不同构造函数的参数为父子关系 */
                    int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
                        argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
                    if (typeDiffWeight < minTypeDiffWeight) { // 如果它代表着当前最接近的匹配,则选择作为构造函数
                        constructorToUse = candidate;
                        argsHolderToUse = argsHolder;
                        argsToUse = argsHolder.arguments;
                        minTypeDiffWeight = typeDiffWeight;
                        ambiguousConstructors = null;
                    } 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(...);
                } else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) 
                    throw new BeanCreationException(...);

                // 将解析的构造函数加入到缓存中
                if (explicitArgs == null && argsHolderToUse != null) 
                    argsHolderToUse.storeCache(mbd, constructorToUse); 
            }
            Assert.state(argsToUse != null, "Unresolved constructor arguments");
            
            /** 步骤3:通过constructorToUse和argsToUse创建bean的实例对象,并存储到BeanWrapper中 */
            bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
            return bw;
        }
    
    
    instantiateBean(...)无参数的实例化构造
        protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
            try {
                Object beanInstance;
                if (System.getSecurityManager() != null) 
                    beanInstance = AccessController.doPrivileged(
                      (PrivilegedAction<Object>) 
                      () -> getInstantiationStrategy().instantiate(mbd, beanName, this), 
                      getAccessControlContext()
                    );
                else 
                    beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);                        实例化策略
                BeanWrapper bw = new BeanWrapperImpl(beanInstance);
                initBeanWrapper(bw);                                                                                   将创建好的实例封装为BeanWrapper对象
                return bw;
            }
            catch (Throwable ex) {throw new BeanCreationException(...);}
        } 
            
    instantiate(...)通过实例化策略类的 instantiate(mbd, beanName, this) 方法创建bean实例对象    
    
        public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
            /** 步骤1:如果没有配置lookup-method或replace-method,则直接使用反射创建bean的实例对象即可 */
            if (!bd.hasMethodOverrides()) {
                Constructor< ?> constructorToUse;
                synchronized (bd.constructorArgumentLock) {
                    constructorToUse = (Constructor< ?>) bd.resolvedConstructorOrFactoryMethod;
                    // 获得构造函数实例
                    if (constructorToUse == null) {
                        final Class< ?> clazz = bd.getBeanClass();
                        if (clazz.isInterface()) throw new BeanInstantiationException(...);
                        try {
                            if (System.getSecurityManager() != null) 
                                constructorToUse = AccessController.doPrivileged((PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
                            else 
                                constructorToUse = clazz.getDeclaredConstructor();
                            bd.resolvedConstructorOrFactoryMethod = constructorToUse;
                        }
                        catch (Throwable ex) {throw new BeanInstantiationException(...);}
                    }
                }
                return BeanUtils.instantiateClass(constructorToUse); // 通过反射创建bean实例
            }
            /** 步骤2:否则,需要使用cglib创建代理对象,将动态方法织入到bean的实例对象中 */
            else 
                return instantiateWithMethodInjection(bd, beanName, owner); // Must generate CGLIB subclass.
        }
    通过 instantiateWithMethodInjection(bd, beanName, owner) 方法,使用cglib创建代理对象
        protected Object instantiateWithMethodInjection(RootBeanDefinition bd, String beanName, BeanFactory owner) {
            return instantiateWithMethodInjection(bd, beanName, owner, null);
        }

        protected Object instantiateWithMethodInjection(RootBeanDefinition bd, String beanName, BeanFactory owner, 
                                                        Constructor< ?> ctor, Object... args) {
            return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
        }

        public Object instantiate(@Nullable Constructor< ?> ctor, Object... args) {
            /** 步骤1:创建Cglib代理类 */
            Class< ?> subclass = createEnhancedSubclass(this.beanDefinition); 

            /** 步骤2:创建Cglib代理类实例对象 */
            Object instance;
            if (ctor == null) instance = BeanUtils.instantiateClass(subclass);
            else {
                try {
                    Constructor< ?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
                    instance = enhancedSubclassConstructor.newInstance(args);
                }
                catch (Exception ex) {...}
            }

            /** 步骤3:将代理对象封装成Factory实例对象,并注入lookup-method和replace-mehtod */
            Factory factory = (Factory) instance;
            factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
                    new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),                        注入lookup-method
                    new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});                     注入replace-mehtod
            return instance;
        }

        private Class< ?> createEnhancedSubclass(RootBeanDefinition beanDefinition) {
            Enhancer enhancer = new Enhancer();
            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);
            return enhancer.createClass();                                                                        创建Cglib代理类
        }
    
    
    

  • 26
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值