SpringBoot 源码阅读(16):createBean

createBean

AbstractAutowireCapableBeanFactory:

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

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

	//解析Class
	// 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.
	Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
	if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
		mbdToUse = new RootBeanDefinition(mbd);
		mbdToUse.setBeanClass(resolvedClass);
	}

	//标记好没有被重写的方法
	// Prepare method overrides.
	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.
		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 {
		Object beanInstance = doCreateBean(beanName, mbdToUse, args);
		if (logger.isTraceEnabled()) {
			logger.trace("Finished creating instance of bean '" + beanName + "'");
		}
		return beanInstance;
	}
	catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
		// A previously detected exception with proper bean creation context already,
		// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
		throw ex;
	}
	catch (Throwable ex) {
		throw new BeanCreationException(
				mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
	}
}

解析Class对象

首先解析Class对象(根据bean定义,类名),这是创建实例的基础。

@Nullable
protected Class<?> resolveBeanClass(RootBeanDefinition mbd, String beanName, Class<?>... typesToMatch) throws CannotLoadBeanClassException {
    try {
        if (mbd.hasBeanClass()) {
            return mbd.getBeanClass();
        } else {
            return System.getSecurityManager() != null ? (Class)AccessController.doPrivileged(() -> {
                return this.doResolveBeanClass(mbd, typesToMatch);
            }, this.getAccessControlContext()) : this.doResolveBeanClass(mbd, typesToMatch);
        }
    } catch (PrivilegedActionException var6) {
        ClassNotFoundException ex = (ClassNotFoundException)var6.getException();
        throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
    } catch (ClassNotFoundException var7) {
        throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), var7);
    } catch (LinkageError var8) {
        throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), var8);
    }
}

准备方法重写

这一步工作其实是标记好没有被重写的方法(名称对应的方法的数量只有1个):

public void prepareMethodOverrides() throws BeanDefinitionValidationException {
    if (this.hasMethodOverrides()) {
        Set<MethodOverride> overrides = this.getMethodOverrides().getOverrides();
        synchronized(overrides) {
            Iterator var3 = overrides.iterator();

            while(var3.hasNext()) {
                MethodOverride mo = (MethodOverride)var3.next();
                this.prepareMethodOverride(mo);
            }
        }
    }

}
protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException {
    int count = ClassUtils.getMethodCountForName(this.getBeanClass(), mo.getMethodName());
    if (count == 0) {
        throw new BeanDefinitionValidationException("Invalid method override: no method with name '" + mo.getMethodName() + "' on class [" + this.getBeanClassName() + "]");
    } else {
        if (count == 1) {
            mo.setOverloaded(false);
        }

    }
}

实例化前处理

在实例化前调用后处理器(见博客),如果得到返回的bean,再调用后处理器后直接返回。
AOP在此实现。

@Nullable
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
    Object bean = null;
    if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
        if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
            Class<?> targetType = this.determineTargetType(beanName, mbd);
            if (targetType != null) {
                bean = this.applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                if (bean != null) {
                    bean = this.applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
            }
        }

        mbd.beforeInstantiationResolved = bean != null;
    }

    return bean;
}

实例化

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
    }
	
	//实例化并封装
    if (instanceWrapper == null) {
        instanceWrapper = this.createBeanInstance(beanName, mbd, args);
    }

	//bean的类型
    Object bean = instanceWrapper.getWrappedInstance();
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
        mbd.resolvedTargetType = beanType;
    }

	//后处理bean定义
    synchronized(mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                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;
        }
    }

		//提前暴露工厂,防止循环引用
		boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
    if (earlySingletonExposure) {
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references");
        }

        this.addSingletonFactory(beanName, () -> {
            return this.getEarlyBeanReference(beanName, mbd, bean);
        });
    }

    Object exposedObject = bean;

    try {
    	//注入属性
        this.populateBean(beanName, mbd, instanceWrapper);
        
        //初始化
        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 (earlySingletonExposure) {
        Object earlySingletonReference = this.getSingleton(beanName, false);
        if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
            } else if (!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
                String[] dependentBeans = this.getDependentBeans(beanName);
                Set<String> 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);
                    }
                }

                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 {
    	//注册DisposableBean
        this.registerDisposableBeanIfNecessary(beanName, bean, mbd);
        return exposedObject;
    } catch (BeanDefinitionValidationException var16) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", var16);
    }
}

实例化bean并封装

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
    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 {
    
        Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
        if (instanceSupplier != null) {     //通过Supplier
            return this.obtainFromSupplier(instanceSupplier, beanName);
        } else if (mbd.getFactoryMethodName() != null) { //通过工厂方法
            return this.instantiateUsingFactoryMethod(beanName, mbd, args);
        } else {
            boolean resolved = false;
            boolean autowireNecessary = false;
            if (args == null) {
                synchronized(mbd.constructorArgumentLock) {
                    if (mbd.resolvedConstructorOrFactoryMethod != null) {
                        resolved = true;
                        autowireNecessary = mbd.constructorArgumentsResolved;
                    }
                }
            }

            if (resolved) {
            	//解析过
                return autowireNecessary ? this.autowireConstructor(beanName, mbd, (Constructor[])null, (Object[])null) : this.instantiateBean(beanName, mbd);
            } else {
                //通过后处理器确定构造方法
                Constructor<?>[] ctors = this.determineConstructorsFromBeanPostProcessors(beanClass, beanName);
                //默认选取(根据参数匹配程度)
                if (ctors == null && mbd.getResolvedAutowireMode() != 3 && !mbd.hasConstructorArgumentValues() && ObjectUtils.isEmpty(args)) {
                    ctors = mbd.getPreferredConstructors();
                    return ctors != null ? this.autowireConstructor(beanName, mbd, ctors, (Object[])null) : this.instantiateBean(beanName, mbd);
                } else {
                    return this.autowireConstructor(beanName, mbd, ctors, args);
                }
            }
        }
    }
}

实例化分为了三种情况:

  1. bean定义了Supplier,通过其get方法获取bean:
protected BeanWrapper obtainFromSupplier(Supplier<?> instanceSupplier, String beanName) {
    String outerBean = (String)this.currentlyCreatedBean.get();
    this.currentlyCreatedBean.set(beanName);

    Object instance;
    try {
        instance = instanceSupplier.get();
    } finally {
        if (outerBean != null) {
            this.currentlyCreatedBean.set(outerBean);
        } else {
            this.currentlyCreatedBean.remove();
        }

    }

    if (instance == null) {
        instance = new NullBean();
    }

    BeanWrapper bw = new BeanWrapperImpl(instance);
    this.initBeanWrapper(bw);
    return bw;
}
  1. 通过工厂方法实例化
    具体实现其实与通过构造方法实例化类似。
protected BeanWrapper instantiateUsingFactoryMethod(String beanName, RootBeanDefinition mbd, @Nullable Object[] explicitArgs) {
    return (new ConstructorResolver(this)).instantiateUsingFactoryMethod(beanName, mbd, explicitArgs);
}
  1. 通过构造方法实例化
    首先确定选用哪个构造方法。
else {
		//通过后处理器选择
        Constructor<?>[] ctors = this.determineConstructorsFromBeanPostProcessors(beanClass, beanName);

		//解析构造方法并实例化
        if (ctors == null && mbd.getResolvedAutowireMode() != 3 && !mbd.hasConstructorArgumentValues() && ObjectUtils.isEmpty(args)) {
            ctors = mbd.getPreferredConstructors();
            return ctors != null ? this.autowireConstructor(beanName, mbd, ctors, (Object[])null) : this.instantiateBean(beanName, mbd);
        } else {
            return this.autowireConstructor(beanName, mbd, ctors, args);
        }
    }

首先通过后处理器(SmartInstantiationAwareBeanPostProcessor)选择,这样程序员可通过编写自己的后处理器选择使用哪个构造方法:

@Nullable
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName) throws BeansException {
    if (beanClass != null && this.hasInstantiationAwareBeanPostProcessors()) {
        Iterator var3 = this.getBeanPostProcessors().iterator();

        while(var3.hasNext()) {
            BeanPostProcessor bp = (BeanPostProcessor)var3.next();
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor)bp;
                Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
                if (ctors != null) {
                    return ctors;
                }
            }
        }
    }

    return null;
}

默认构造方法的选取就会比较复杂:

protected BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {
    return (new ConstructorResolver(this)).autowireConstructor(beanName, mbd, ctors, explicitArgs);
}

这段代码很长,这里只关注了整体的逻辑,大致就是先确定使用的参数,然后根据匹配程度选择最匹配的构造方法:

public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
    BeanWrapperImpl bw = new BeanWrapperImpl();
    this.beanFactory.initBeanWrapper(bw);
    
    //使用的构造方法
    Constructor<?> constructorToUse = null;
    //使用的参数持有者
    ConstructorResolver.ArgumentsHolder argsHolderToUse = null;
    //使用的参数
    Object[] argsToUse = null;
    
    if (explicitArgs != null) {
    	//构造参数已经明确声明
        argsToUse = explicitArgs;
    } else {
        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) {
            argsToUse = this.resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve, true);
        }
    }

    if (constructorToUse == null || argsToUse == null) {
		
		//首先获取所有的构造方法
        Constructor<?>[] candidates = chosenCtors;
        if (chosenCtors == null) {
            Class beanClass = mbd.getBeanClass();
            try {
                candidates = mbd.isNonPublicAccessAllowed() ? beanClass.getDeclaredConstructors() : beanClass.getConstructors();
            } catch (Throwable var25) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Resolution of declared constructors on bean Class [" + beanClass.getName() + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", var25);
            }
        }

		//只有一个候选构造方法,声明无参数,该构造方法也无参数,实例化即可
        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(this.instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
                return bw;
            }
        }

		//确定构造参数最少的个数
        boolean autowiring = chosenCtors != null || mbd.getResolvedAutowireMode() == 3;
        ConstructorArgumentValues resolvedValues = null;
        int minNrOfArgs;
        if (explicitArgs != null) {
            minNrOfArgs = explicitArgs.length;
        } else {
            ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
            resolvedValues = new ConstructorArgumentValues();
            //解析构造参数
            minNrOfArgs = this.resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
        }

		//对候选构造方法排序(public在前、参数个数多的在前)
        AutowireUtils.sortConstructors(candidates);
        
        int minTypeDiffWeight = 2147483647;
        Set<Constructor<?>> ambiguousConstructors = null;
        LinkedList<UnsatisfiedDependencyException> causes = null;
        Constructor[] var16 = candidates;
        int var17 = candidates.length;

        for(int var18 = 0; var18 < var17; ++var18) {
            Constructor<?> candidate = var16[var18];
            Class<?>[] paramTypes = candidate.getParameterTypes();
            //该方法所需的参数少于使用的参数的个数,由于已排过序,直接跳出循环
            if (constructorToUse != null && argsToUse != null && argsToUse.length > paramTypes.length) {
                break;
            }

            if (paramTypes.length >= minNrOfArgs) {
                ConstructorResolver.ArgumentsHolder argsHolder;
                if (resolvedValues != null) {
                    try {
                    	//获取方法的参数名称
                        String[] paramNames = ConstructorResolver.ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length);
                        if (paramNames == null) {
                            ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                            if (pnd != null) {
                                paramNames = pnd.getParameterNames(candidate);
                            }
                        }
							
						//参数持有者
                        argsHolder = this.createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames, this.getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
                    } catch (UnsatisfiedDependencyException var26) {
                        if (this.logger.isTraceEnabled()) {
                            this.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 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) {
                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 ex = (UnsatisfiedDependencyException)causes.removeLast();
            Iterator var33 = causes.iterator();

            while(var33.hasNext()) {
                Exception cause = (Exception)var33.next();
                this.beanFactory.onSuppressedException(cause);
            }

            throw ex;
        }

        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 != null) {
            argsHolderToUse.storeCache(mbd, constructorToUse);
        }
    }

    Assert.state(argsToUse != null, "Unresolved constructor arguments");
    
    //实例化并封装
    bw.setBeanInstance(this.instantiate(beanName, mbd, constructorToUse, argsToUse));
    return bw;
}

构造方法的排序:

public static void sortConstructors(Constructor<?>[] constructors) {
    Arrays.sort(constructors, (c1, c2) -> {
        boolean p1 = Modifier.isPublic(c1.getModifiers());
        boolean p2 = Modifier.isPublic(c2.getModifiers());
        if (p1 != p2) {
            return p1 ? -1 : 1;
        } else {
            int c1pl = c1.getParameterCount();
            int c2pl = c2.getParameterCount();
            return c1pl < c2pl ? 1 : (c1pl > c2pl ? -1 : 0);
        }
    });
}

实例化:

private Object instantiate(String beanName, RootBeanDefinition mbd, Constructor constructorToUse, Object[] argsToUse) {
    try {
        InstantiationStrategy strategy = this.beanFactory.getInstantiationStrategy();
        return System.getSecurityManager() != null ? AccessController.doPrivileged(() -> {
            return strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
        }, this.beanFactory.getAccessControlContext()) : strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
    } catch (Throwable var6) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean instantiation via constructor failed", var6);
    }
}

后处理bean的定义

后处理器的调用都是类似的,重点在于各后处理器实现的具体功能。

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
    Iterator var4 = this.getBeanPostProcessors().iterator();

    while(var4.hasNext()) {
        BeanPostProcessor bp = (BeanPostProcessor)var4.next();
        if (bp instanceof MergedBeanDefinitionPostProcessor) {
            MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor)bp;
            bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
        }
    }

}

提前暴露工厂,防止循环引用

	//提前暴露工厂,防止循环引用
	boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
if (earlySingletonExposure) {
    if (this.logger.isTraceEnabled()) {
        this.logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references");
    }

    this.addSingletonFactory(beanName, () -> {
        return this.getEarlyBeanReference(beanName, mbd, bean);
    });
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
    Object exposedObject = bean;
    if (!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);
            }
        }
    }

    return exposedObject;
}

循环引用上一篇已经提过了,这里我们可以更清楚的知道,暴露工厂是在调用构造方法后,setter之前。

属性注入

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 {
        boolean continueWithPropertyPopulation = true;
        if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
        
        	//调用后处理器
            Iterator var5 = this.getBeanPostProcessors().iterator();
            while(var5.hasNext()) {
                BeanPostProcessor bp = (BeanPostProcessor)var5.next();
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp;
                    if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                        continueWithPropertyPopulation = false;
                        break;
                    }
                }
            }
        }

        if (continueWithPropertyPopulation) {
            PropertyValues pvs = mbd.hasPropertyValues() ? mbd.getPropertyValues() : null;
            if (mbd.getResolvedAutowireMode() == 1 || mbd.getResolvedAutowireMode() == 2) {
            	//确定填充的值
                MutablePropertyValues newPvs = new MutablePropertyValues((PropertyValues)pvs);
                if (mbd.getResolvedAutowireMode() == 1) {
                	//根据名称填充
                    this.autowireByName(beanName, mbd, bw, newPvs);
                }

                if (mbd.getResolvedAutowireMode() == 2) {
                	//根据类型填充
                    this.autowireByType(beanName, mbd, bw, newPvs);
                }
                pvs = newPvs;
            }

			//对填充的属性值进行后处理
            boolean hasInstAwareBpps = this.hasInstantiationAwareBeanPostProcessors();
            boolean needsDepCheck = mbd.getDependencyCheck() != 0;
            PropertyDescriptor[] filteredPds = null;
            if (hasInstAwareBpps) {
                if (pvs == null) {
                    pvs = mbd.getPropertyValues();
                }

                Iterator var9 = this.getBeanPostProcessors().iterator();

                while(var9.hasNext()) {
                    BeanPostProcessor bp = (BeanPostProcessor)var9.next();
                    if (bp instanceof InstantiationAwareBeanPostProcessor) {
                        InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp;
                        PropertyValues pvsToUse = ibp.postProcessProperties((PropertyValues)pvs, bw.getWrappedInstance(), beanName);
                        if (pvsToUse == null) {
                            if (filteredPds == null) {
                                filteredPds = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                            }

                            pvsToUse = ibp.postProcessPropertyValues((PropertyValues)pvs, filteredPds, bw.getWrappedInstance(), beanName);
                            if (pvsToUse == null) {
                                return;
                            }
                        }

                        pvs = pvsToUse;
                    }
                }
            }

			//依赖检查
            if (needsDepCheck) {
                if (filteredPds == null) {
                    filteredPds = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                }

                this.checkDependencies(beanName, mbd, filteredPds, (PropertyValues)pvs);
            }

			//属性注入
            if (pvs != null) {
                this.applyPropertyValues(beanName, mbd, bw, (PropertyValues)pvs);
            }

        }
    }
}

首先又看到了后处理器,通过后处理器返回可以控制是否进行属性填充、
接下来确定填充的值:
根据名称填充:
逻辑很简单,根据未满足属性的名称寻找相应的bean:

protected void autowireByName(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    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)) {
            Object bean = this.getBean(propertyName);
            pvs.add(propertyName, bean);
            this.registerDependentBean(propertyName, beanName);
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("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");
        }
    }

}

根据类型填充:
这一步需要注意的是,通过set方法注入的属性,set的参数不一定是该属性,且可能有多个,set方法内部可能做些处理,故需获得写方法的参数,然后解析获得相应类型的bean实例。

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

    Set<String> autowiredBeanNames = new LinkedHashSet(4);
    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 pd = bw.getPropertyDescriptor(propertyName);
            if (Object.class != pd.getPropertyType()) {
            	//写方法的参数
                MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
                
                boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
                DependencyDescriptor desc = new AbstractAutowireCapableBeanFactory.AutowireByTypeDependencyDescriptor(methodParam, eager);
               
               //解析写方法参数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.isTraceEnabled()) {
                        this.logger.trace("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);
        }
    }

}

之后对获取到的属性值后处理,进行依赖检查后将属性注入:

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

        MutablePropertyValues mpvs = null;
        List original;
        if (pvs instanceof MutablePropertyValues) {
            mpvs = (MutablePropertyValues)pvs;
            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 {
            original = Arrays.asList(pvs.getPropertyValues());
        }

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

        BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, (TypeConverter)converter);
        List<PropertyValue> deepCopy = new ArrayList(original.size());
        boolean resolveNecessary = false;
        Iterator var11 = original.iterator();

        while(true) {
            while(var11.hasNext()) {
                PropertyValue pv = (PropertyValue)var11.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);
            }
        }
    }
}

初始化

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {

	//注入Spring相关资源
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(() -> {
            this.invokeAwareMethods(beanName, bean);
            return null;
        }, this.getAccessControlContext());
    } else {
        this.invokeAwareMethods(beanName, bean);
    }

	//后处理器
    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
    }

	//调用初始化方法
    try {
        this.invokeInitMethods(beanName, wrappedBean, mbd);
    } catch (Throwable var6) {
        throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
    }

	//后处理器
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }

    return wrappedBean;
}

首先根据实现接口注入Spring相关资源:

private void invokeAwareMethods(String beanName, Object bean) {
    if (bean instanceof Aware) {
        if (bean instanceof BeanNameAware) {
            ((BeanNameAware)bean).setBeanName(beanName);
        }

        if (bean instanceof BeanClassLoaderAware) {
            ClassLoader bcl = this.getBeanClassLoader();
            if (bcl != null) {
                ((BeanClassLoaderAware)bean).setBeanClassLoader(bcl);
            }
        }

        if (bean instanceof BeanFactoryAware) {
            ((BeanFactoryAware)bean).setBeanFactory(this);
        }
    }

}

在调用初始化方法前后调用后处理器,这一点看过很多类似的了,主要为了扩展,看下初始化方法的调用:
分成两块:

  1. 实现InitializingBean,调用afterPropertiesSet
  2. 调用自定义初始化方法
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd) throws Throwable {
	//实现InitializingBean,调用afterPropertiesSet
    boolean isInitializingBean = bean instanceof InitializingBean;
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }

        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged(() -> {
                    ((InitializingBean)bean).afterPropertiesSet();
                    return null;
                }, this.getAccessControlContext());
            } catch (PrivilegedActionException var6) {
                throw var6.getException();
            }
        } else {
            ((InitializingBean)bean).afterPropertiesSet();
        }
    }

	//调用自定义初始化方法
    if (mbd != null && bean.getClass() != NullBean.class) {
        String initMethodName = mbd.getInitMethodName();
        if (StringUtils.hasLength(initMethodName) && (!isInitializingBean || !"afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) {
            this.invokeCustomInitMethod(beanName, bean, mbd);
        }
    }

}

循环依赖检测

这一部分主要就是进行循环依赖检测,如果检测到异常(依赖的bean,do not use the final version of the bean),抛出:

if (earlySingletonExposure) {
    Object earlySingletonReference = this.getSingleton(beanName, false);
    if (earlySingletonReference != null) {
        if (exposedObject == bean) {
            exposedObject = earlySingletonReference;
        } else if (!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
            String[] dependentBeans = this.getDependentBeans(beanName);
            Set<String> 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);
                }
            }

            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.");
            }
        }
    }
}

注册DisposableBean

如果bean销毁前需要处理,进行注册:

protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
    AccessControlContext acc = System.getSecurityManager() != null ? this.getAccessControlContext() : null;
    if (!mbd.isPrototype() && this.requiresDestruction(bean, mbd)) {
        if (mbd.isSingleton()) {
            this.registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, this.getBeanPostProcessors(), acc));
        } else {
            Scope scope = (Scope)this.scopes.get(mbd.getScope());
            if (scope == null) {
                throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
            }

            scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, this.getBeanPostProcessors(), acc));
        }
    }

}
protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
    return bean.getClass() != NullBean.class && (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || this.hasDestructionAwareBeanPostProcessors() && DisposableBeanAdapter.hasApplicableProcessors(bean, this.getBeanPostProcessors()));
}
public void registerDisposableBean(String beanName, DisposableBean bean) {
    synchronized(this.disposableBeans) {
        this.disposableBeans.put(beanName, bean);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值