spring学习之源码分析–AbstractAutowireCapableBeanFactory

AbstractAutowireCapableBeanFactory

抽象类AbstractAutowireCapableBeanFactory继承了AbstractBeanFactory类,以及实现了 AutowireCapableBeanFactory 的接口。

类结构

spring学习之源码分析--AbstractAutowireCapableBeanFactory

常量

// bean的生成策略,默认CGLIB
private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
// 解析策略的方法参数
private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
// 尝试解析循环引用
private boolean allowCircularReferences = true;
// 在循环引用的情况下,是否需要注入一个原始的bean实例
private boolean allowRawInjectionDespiteWrapping = false;
// 依赖项检查和自动装配时忽略的依赖项类型
private final Set<Class<?>> ignoredDependencyTypes = new HashSet<>();
// 依赖项检查和自动装配时忽略的依赖项接口
private final Set<Class<?>> ignoredDependencyInterfaces = new HashSet<>();
// 当前正在创建的bean
private final NamedThreadLocal<String> currentlyCreatedBean = new NamedThreadLocal<>("Currently created bean");
// beanName和FactoryBean的映射
private final ConcurrentMap<String, BeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<>();
// 类和候选方法映射
private final ConcurrentMap<Class<?>, Method[]> factoryMethodCandidateCache = new ConcurrentHashMap<>();
// 类和PropertyDescriptor的映射
private final ConcurrentMap<Class<?>, PropertyDescriptor[]> filteredPropertyDescriptorsCache = new ConcurrentHashMap<>();

方法解析

AbstractAutowireCapableBeanFactory

构造函数,忽略BeanNameAware、BeanFactoryAware、BeanClassLoaderAware的依赖

public AbstractAutowireCapableBeanFactory() {
    super();
    ignoreDependencyInterface(BeanNameAware.class);
    ignoreDependencyInterface(BeanFactoryAware.class);
    ignoreDependencyInterface(BeanClassLoaderAware.class);
}
public AbstractAutowireCapableBeanFactory(@Nullable BeanFactory parentBeanFactory) {
    this();
    setParentBeanFactory(parentBeanFactory);
}

setInstantiationStrategy

getInstantiationStrategy

生成策略的设值与获取

public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
    this.instantiationStrategy = instantiationStrategy;
}
protected InstantiationStrategy getInstantiationStrategy() {
    return this.instantiationStrategy;
}

setParameterNameDiscoverer

getParameterNameDiscoverer

解析策略的方法参数的设值与获取

public void setParameterNameDiscoverer(@Nullable ParameterNameDiscoverer parameterNameDiscoverer) {
    this.parameterNameDiscoverer = parameterNameDiscoverer;
}
protected ParameterNameDiscoverer getParameterNameDiscoverer() {
    return this.parameterNameDiscoverer;
}

setAllowCircularReferences

尝试解析循环引用

public void setAllowCircularReferences(boolean allowCircularReferences) {
    this.allowCircularReferences = allowCircularReferences;
}

setAllowRawInjectionDespiteWrapping

在循环引用的情况下,是否需要注入一个原始的bean实例

public void setAllowRawInjectionDespiteWrapping(boolean allowRawInjectionDespiteWrapping) {
    this.allowRawInjectionDespiteWrapping = allowRawInjectionDespiteWrapping;
}

ignoreDependencyType

依赖项检查和自动装配时忽略的依赖项类型

public void ignoreDependencyType(Class<?> type) {
    this.ignoredDependencyTypes.add(type);
}

ignoreDependencyInterface

依赖项检查和自动装配时忽略的依赖项接口

public void ignoreDependencyInterface(Class<?> ifc) {
    this.ignoredDependencyInterfaces.add(ifc);
}

copyConfigurationFrom

除了复制父类的几种配置,好包括了instantiationStrategy、allowCircularReferences、ignoredDependencyTypes、ignoredDependencyInterfaces

public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
    super.copyConfigurationFrom(otherFactory);
    if (otherFactory instanceof AbstractAutowireCapableBeanFactory) {
        AbstractAutowireCapableBeanFactory otherAutowireFactory =
                (AbstractAutowireCapableBeanFactory) otherFactory;
        this.instantiationStrategy = otherAutowireFactory.instantiationStrategy;
        this.allowCircularReferences = otherAutowireFactory.allowCircularReferences;
        this.ignoredDependencyTypes.addAll(otherAutowireFactory.ignoredDependencyTypes);
        this.ignoredDependencyInterfaces.addAll(otherAutowireFactory.ignoredDependencyInterfaces);
    }
}

createBean

创建bean

public <T> T createBean(Class<T> beanClass) throws BeansException {
    // Use prototype bean definition, to avoid registering bean as dependent bean.
    // 封装到BeanDefinition
    RootBeanDefinition bd = new RootBeanDefinition(beanClass);
    bd.setScope(SCOPE_PROTOTYPE);
    // 是否允许缓存
    bd.allowCaching = ClassUtils.isCacheSafe(beanClass, getBeanClassLoader());
    return (T) createBean(beanClass.getName(), bd, null);
}
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;

    // 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
    Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
        // 不为空,且mbd没有类信息,重新设值
        mbdToUse = new RootBeanDefinition(mbd);
        mbdToUse.setBeanClass(resolvedClass);
    }

    // Prepare method overrides.
    try {
        // 之前的lookup注解或者<lookup-method /> 标签就是这里实现的,还有<replaced-method />
        mbdToUse.prepareMethodOverrides();
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                beanName, "Validation of method overrides failed", ex);
    }

    try {
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
        // 前置处理器是否返回bean
        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
        if (bean != null) {
            return bean;
        }
    }
    catch (Throwable ex) {
        throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                "BeanPostProcessor before instantiation of bean failed", ex);
    }

    try {
        // 创建bean
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.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);
    }
}
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
            throws BeanCreationException {

    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        // 返回空,说明不是FactoryBean
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    // 获取bean的实例
    final Object bean = instanceWrapper.getWrappedInstance();
    // 获取bean的类型
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
        mbd.resolvedTargetType = beanType;
    }

    // Allow post-processors to modify the merged bean definition.
    // 后置处理器修改合并bean的定义
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }

    // Eagerly cache singletons to be able to resolve circular references
    // even when triggered by lifecycle interfaces like BeanFactoryAware.
    // 循环依赖
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
            isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
        if (logger.isTraceEnabled()) {
            logger.trace("Eagerly caching bean '" + beanName +
                    "' to allow for resolving potential circular references");
        }
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
        // 实例化后,对bean进行赋值
        populateBean(beanName, mbd, instanceWrapper);
        // 赋值后,调用init方法,InitializingBean这些
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
    catch (Throwable ex) {
        if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
            throw (BeanCreationException) ex;
        }
        else {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
        }
    }

    if (earlySingletonExposure) {
        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(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.");
                }
            }
        }
    }

    // Register bean as disposable.
    try {
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }

    return exposedObject;
}

autowireBean

给bean的属性赋值

public void autowireBean(Object existingBean) {
    // Use non-singleton bean definition, to avoid registering bean as dependent bean.
    RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean));
    bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
    bd.allowCaching = ClassUtils.isCacheSafe(bd.getBeanClass(), getBeanClassLoader());
    BeanWrapper bw = new BeanWrapperImpl(existingBean);
    // 初始化BeanWrapper
    initBeanWrapper(bw);
    // 给bean的属性赋值
    populateBean(bd.getBeanClass().getName(), bd, bw);
}

configureBean

public Object configureBean(Object existingBean, String beanName) throws BeansException {
    // 如果已经创建了,bean的定义要清除
    markBeanAsCreated(beanName);
    // 重新设置bean的定义
    BeanDefinition mbd = getMergedBeanDefinition(beanName);
    RootBeanDefinition bd = null;
    if (mbd instanceof RootBeanDefinition) {
        RootBeanDefinition rbd = (RootBeanDefinition) mbd;
        bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition());
    }
    if (bd == null) {
        bd = new RootBeanDefinition(mbd);
    }
    if (!bd.isPrototype()) {
        bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
        bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader());
    }
    BeanWrapper bw = new BeanWrapperImpl(existingBean);
    // 初始化BeanWrapper
    initBeanWrapper(bw);
    // 给bean的属性赋值
    populateBean(beanName, bd, bw);
    // 调用init方法,InitializingBean这些
    return initializeBean(beanName, existingBean, bd);
}

autowire

使用指定的自动装配策略实例化给定类的新bean实例

public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
    // Use non-singleton bean definition, to avoid registering bean as dependent bean.
    final RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
    bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
    // 如果是构造器注入
    if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) {
        return autowireConstructor(beanClass.getName(), bd, null, null).getWrappedInstance();
    }
    else {
        Object bean;
        final BeanFactory parent = this;
        if (System.getSecurityManager() != null) {
            bean = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
                    getInstantiationStrategy().instantiate(bd, null, parent),
                    getAccessControlContext());
        }
        else {
            // 生成bean
            bean = getInstantiationStrategy().instantiate(bd, null, parent);
        }
        // 给bean的属性赋值
        populateBean(beanClass.getName(), bd, new BeanWrapperImpl(bean));
        return bean;
    }
}

autowireBeanProperties

根据名称或类型自动装配给定bean实例的bean属性。

public void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)
        throws BeansException {

    if (autowireMode == AUTOWIRE_CONSTRUCTOR) {
        throw new IllegalArgumentException("AUTOWIRE_CONSTRUCTOR not supported for existing bean instance");
    }
    // Use non-singleton bean definition, to avoid registering bean as dependent bean.
    RootBeanDefinition bd =
            new RootBeanDefinition(ClassUtils.getUserClass(existingBean), autowireMode, dependencyCheck);
    bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
    BeanWrapper bw = new BeanWrapperImpl(existingBean);
    initBeanWrapper(bw);
    // 给bean的属性赋值
    populateBean(bd.getBeanClass().getName(), bd, bw);
}

applyBeanPropertyValues

将具有给定名称的bean定义的属性值应用于给定的bean实例

public void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException {
    markBeanAsCreated(beanName);
    BeanDefinition bd = getMergedBeanDefinition(beanName);
    BeanWrapper bw = new BeanWrapperImpl(existingBean);
    initBeanWrapper(bw);
    applyPropertyValues(beanName, bd, bw, bd.getPropertyValues());
}

initializeBean

public Object initializeBean(Object existingBean, String beanName) {
    return initializeBean(beanName, existingBean, null);
}
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            invokeAwareMethods(beanName, bean);
            return null;
        }, getAccessControlContext());
    }
    else {
        // 调用BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
        invokeAwareMethods(beanName, bean);
    }

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

    try {
        // 初始化方法
        invokeInitMethods(beanName, wrappedBean, mbd);
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
                (mbd != null ? mbd.getResourceDescription() : null),
                beanName, "Invocation of init method failed", ex);
    }
    if (mbd == null || !mbd.isSynthetic()) {
        // 后置处理器
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }

    return wrappedBean;
}

applyBeanPostProcessorsBeforeInitialization

前置处理器

public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
        throws BeansException {

    Object result = existingBean;
    // 获取BeanPostProcessor处理
    for (BeanPostProcessor processor : getBeanPostProcessors()) {
        Object current = processor.postProcessBeforeInitialization(result, beanName);
        if (current == null) {
            return result;
        }
        result = current;
    }
    return result;
}

applyBeanPostProcessorsAfterInitialization

后置处理器

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
        throws BeansException {

    Object result = existingBean;
    // 获取BeanPostProcessor处理
    for (BeanPostProcessor processor : getBeanPostProcessors()) {
        Object current = processor.postProcessAfterInitialization(result, beanName);
        if (current == null) {
            return result;
        }
        result = current;
    }
    return result;
}

destroyBean

销毁bean

public void destroyBean(Object existingBean) {
    new DisposableBeanAdapter(existingBean, getBeanPostProcessors(), getAccessControlContext()).destroy();
}

resolveBeanByName

解析给定bean名称的bean实例,为目标工厂方法提供依赖描述符。

public Object resolveBeanByName(String name, DependencyDescriptor descriptor) {
    InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
    try {
        // 获取bean
        return getBean(name, descriptor.getDependencyType());
    }
    finally {
        // 为目标工厂方法提供依赖描述符
        ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
    }
}

resolveDependency

根据工厂中定义的bean解析指定的依赖项。

public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName) throws BeansException {
    return resolveDependency(descriptor, requestingBeanName, null, null);
}

predictBeanType

预测bean类型

protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
    // 确定给定bean定义的目标类型。
    Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch);

    // Apply SmartInstantiationAwareBeanPostProcessors to predict the
    // eventual type after a before-instantiation shortcut.
    // 通过SmartInstantiationAwareBeanPostProcessors获取实际类型
    if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                Class<?> predicted = ibp.predictBeanType(targetType, beanName);
                if (predicted != null && (typesToMatch.length != 1 || FactoryBean.class != typesToMatch[0] ||
                        FactoryBean.class.isAssignableFrom(predicted))) {
                    return predicted;
                }
            }
        }
    }
    return targetType;
}

determineTargetType

确定给定bean定义的目标类型。

protected Class<?> determineTargetType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
    Class<?> targetType = mbd.getTargetType();
    if (targetType == null) {
        targetType = (mbd.getFactoryMethodName() != null ?
                getTypeForFactoryMethod(beanName, mbd, typesToMatch) :
                resolveBeanClass(mbd, beanName, typesToMatch));
        if (ObjectUtils.isEmpty(typesToMatch) || getTempClassLoader() == null) {
            mbd.resolvedTargetType = targetType;
        }
    }
    return targetType;
}

getTypeForFactoryMethod

确定基于工厂方法的给定bean定义的目标类型。只有在没有为目标bean注册单例实例时才调用

protected Class<?> getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
    // 获取目标方法返回类型
    ResolvableType cachedReturnType = mbd.factoryMethodReturnType;
    if (cachedReturnType != null) {
        return cachedReturnType.resolve();
    }

    Class<?> factoryClass;
    boolean isStatic = true;

    String factoryBeanName = mbd.getFactoryBeanName();
    if (factoryBeanName != null) {
        // factoryBean的情况
        if (factoryBeanName.equals(beanName)) {
            throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
                    "factory-bean reference points back to the same bean definition");
        }
        // Check declared factory method return type on factory class.
        // 获取指定beanName的类型
        factoryClass = getType(factoryBeanName);
        isStatic = false;
    }
    else {
        // Check declared factory method return type on bean class.
        // 解析类名
        factoryClass = resolveBeanClass(mbd, beanName, typesToMatch);
    }

    if (factoryClass == null) {
        return null;
    }
    factoryClass = ClassUtils.getUserClass(factoryClass);

    // If all factory methods have the same return type, return that type.
    // Can't clearly figure out exact method due to type converting / autowiring!
    Class<?> commonType = null;
    Method uniqueCandidate = null;
    // 获取构造函数的参数个数
    int minNrOfArgs =
            (mbd.hasConstructorArgumentValues() ? mbd.getConstructorArgumentValues().getArgumentCount() : 0);
    // 方法候选
    Method[] candidates = this.factoryMethodCandidateCache.computeIfAbsent(
            factoryClass, ReflectionUtils::getUniqueDeclaredMethods);
    // 有多个的情况,需要遍历查找
    for (Method candidate : candidates) {
        if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate) &&
                candidate.getParameterCount() >= minNrOfArgs) {
            // Declared type variables to inspect?
            if (candidate.getTypeParameters().length > 0) {
                try {
                    // Fully resolve parameter names and argument values.
                    // 解析参数名和参数值
                    Class<?>[] paramTypes = candidate.getParameterTypes();
                    String[] paramNames = null;
                    ParameterNameDiscoverer pnd = getParameterNameDiscoverer();
                    if (pnd != null) {
                        paramNames = pnd.getParameterNames(candidate);
                    }
                    ConstructorArgumentValues cav = mbd.getConstructorArgumentValues();
                    Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>(paramTypes.length);
                    Object[] args = new Object[paramTypes.length];
                    for (int i = 0; i < args.length; i++) {
                        ConstructorArgumentValues.ValueHolder valueHolder = cav.getArgumentValue(
                                i, paramTypes[i], (paramNames != null ? paramNames[i] : null), usedValueHolders);
                        if (valueHolder == null) {
                            valueHolder = cav.getGenericArgumentValue(null, null, usedValueHolders);
                        }
                        if (valueHolder != null) {
                            args[i] = valueHolder.getValue();
                            usedValueHolders.add(valueHolder);
                        }
                    }
                    Class<?> returnType = AutowireUtils.resolveReturnTypeForFactoryMethod(
                            candidate, args, getBeanClassLoader());
                    uniqueCandidate = (commonType == null && returnType == candidate.getReturnType() ?
                            candidate : null);
                    commonType = ClassUtils.determineCommonAncestor(returnType, commonType);
                    if (commonType == null) {
                        // Ambiguous return types found: return null to indicate "not determinable".
                        return null;
                    }
                }
                catch (Throwable ex) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Failed to resolve generic return type for factory method: " + ex);
                    }
                }
            }
            else {
                uniqueCandidate = (commonType == null ? candidate : null);
                commonType = ClassUtils.determineCommonAncestor(candidate.getReturnType(), commonType);
                if (commonType == null) {
                    // Ambiguous return types found: return null to indicate "not determinable".
                    return null;
                }
            }
        }
    }

    mbd.factoryMethodToIntrospect = uniqueCandidate;
    if (commonType == null) {
        return null;
    }
    // Common return type found: all factory methods return same type. For a non-parameterized
    // unique candidate, cache the full type declaration context of the target factory method.
    cachedReturnType = (uniqueCandidate != null ?
            ResolvableType.forMethodReturnType(uniqueCandidate) : ResolvableType.forClass(commonType));
    mbd.factoryMethodReturnType = cachedReturnType;
    return cachedReturnType.resolve();
}

getTypeForFactoryBean

获取FactoryBean的类型

protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
    if (mbd.getInstanceSupplier() != null) {
        ResolvableType targetType = mbd.targetType;
        if (targetType != null) {
            Class<?> result = targetType.as(FactoryBean.class).getGeneric().resolve();
            if (result != null) {
                // 如果是FactoryBean就返回
                return result;
            }
        }
        if (mbd.hasBeanClass()) {
            Class<?> result = GenericTypeResolver.resolveTypeArgument(mbd.getBeanClass(), FactoryBean.class);
            if (result != null) {
                return result;
            }
        }
    }

    String factoryBeanName = mbd.getFactoryBeanName();
    String factoryMethodName = mbd.getFactoryMethodName();

    if (factoryBeanName != null) {
        if (factoryMethodName != null) {
            // Try to obtain the FactoryBean's object type from its factory method declaration
            // without instantiating the containing bean at all.
            // 从声明中获取FactoryBean的对象类型
            BeanDefinition fbDef = getBeanDefinition(factoryBeanName);
            if (fbDef instanceof AbstractBeanDefinition) {
                AbstractBeanDefinition afbDef = (AbstractBeanDefinition) fbDef;
                if (afbDef.hasBeanClass()) {
                    Class<?> result = getTypeForFactoryBeanFromMethod(afbDef.getBeanClass(), factoryMethodName);
                    if (result != null) {
                        return result;
                    }
                }
            }
        }
        // If not resolvable above and the referenced factory bean doesn't exist yet,
        // exit here - we don't want to force the creation of another bean just to
        // obtain a FactoryBean's object type...
        // 定义中没有,且没有创建过返回空
        if (!isBeanEligibleForMetadataCaching(factoryBeanName)) {
            return null;
        }
    }

    // Let's obtain a shortcut instance for an early getObjectType() call...
    // 如果是单例的,通过单例类型的方法获取FactoryBean,如果是多例的,通过多例类型的方法获取FactoryBean
    FactoryBean<?> fb = (mbd.isSingleton() ?
            getSingletonFactoryBeanForTypeCheck(beanName, mbd) :
            getNonSingletonFactoryBeanForTypeCheck(beanName, mbd));

    if (fb != null) {
        // Try to obtain the FactoryBean's object type from this early stage of the instance.
        // 已经有FactoryBean实例,调用他的getObjectType方法
        Class<?> result = getTypeForFactoryBean(fb);
        if (result != null) {
            return result;
        }
        else {
            // No type found for shortcut FactoryBean instance:
            // fall back to full creation of the FactoryBean instance.
            // 没有获取到通过beanName和定义获取FactoryBean的类型
            return super.getTypeForFactoryBean(beanName, mbd);
        }
    }

    if (factoryBeanName == null && mbd.hasBeanClass()) {
        // No early bean instantiation possible: determine FactoryBean's type from
        // static factory method signature or from class inheritance hierarchy...
        if (factoryMethodName != null) {
            return getTypeForFactoryBeanFromMethod(mbd.getBeanClass(), factoryMethodName);
        }
        else {
            return GenericTypeResolver.resolveTypeArgument(mbd.getBeanClass(), FactoryBean.class);
        }
    }

    return null;
}

getTypeForFactoryBeanFromMethod

查询FactoryBean的通用参数元数据(如果存在的话)以确定对象类型

private Class<?> getTypeForFactoryBeanFromMethod(Class<?> beanClass, final String factoryMethodName) {

    /**
     * Holder used to keep a reference to a {@code Class} value.
     */
    class Holder {

        @Nullable
        Class<?> value = null;
    }

    final Holder objectType = new Holder();

    // CGLIB subclass methods hide generic parameters; look at the original user class.
    Class<?> fbClass = ClassUtils.getUserClass(beanClass);

    // Find the given factory method, taking into account that in the case of
    // @Bean methods, there may be parameters present.
    ReflectionUtils.doWithMethods(fbClass, method -> {
        if (method.getName().equals(factoryMethodName) &&
                FactoryBean.class.isAssignableFrom(method.getReturnType())) {
            Class<?> currentType = GenericTypeResolver.resolveReturnTypeArgument(method, FactoryBean.class);
            if (currentType != null) {
                objectType.value = ClassUtils.determineCommonAncestor(currentType, objectType.value);
            }
        }
    });

    return (objectType.value != null && Object.class != objectType.value ? objectType.value : null);
}

getEarlyBeanReference

获取指定bean的早期访问引用,通常用于解析循环引用。

protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
    Object exposedObject = bean;
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
            }
        }
    }
    return exposedObject;
}

getSingletonFactoryBeanForTypeCheck

单例的话,获取FactoryBean

private FactoryBean<?> getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
    // 加
    synchronized (getSingletonMutex()) {
        // 是否已经实例化
        BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName);
        if (bw != null) {
            // 实例化直接返回
            return (FactoryBean<?>) bw.getWrappedInstance();
        }
        // factoryBeanInstanceCache没有,看看是否已经创建
        Object beanInstance = getSingleton(beanName, false);
        // 创建好的单例是FactoryBean,直接返回
        if (beanInstance instanceof FactoryBean) {
            return (FactoryBean<?>) beanInstance;
        }
        // 创建好的单例不是FactoryBean,或者已经创建或者正在创建,返回空
        if (isSingletonCurrentlyInCreation(beanName) ||
                (mbd.getFactoryBeanName() != null && isSingletonCurrentlyInCreation(mbd.getFactoryBeanName()))) {
            return null;
        }
        // 
        Object instance;
        try {
            // Mark this bean as currently in creation, even if just partially.
            // 创建前检查
            beforeSingletonCreation(beanName);
            // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
            // 看看代理能不能返回一个实例
            instance = resolveBeforeInstantiation(beanName, mbd);
            if (instance == null) {
                // 代理没返回,就创建一个
                bw = createBeanInstance(beanName, mbd, null);
                instance = bw.getWrappedInstance();
            }
        }
        catch (UnsatisfiedDependencyException ex) {
            // Don't swallow, probably misconfiguration...
            throw ex;
        }
        catch (BeanCreationException ex) {
            // Instantiation failure, maybe too early...
            if (logger.isDebugEnabled()) {
                logger.debug("Bean creation exception on singleton FactoryBean type check: " + ex);
            }
            onSuppressedException(ex);
            return null;
        }
        finally {
            // Finished partial creation of this bean.
            // 创建后检查
            afterSingletonCreation(beanName);
        }
        // 获取到的实例转换为FactoryBean
        FactoryBean<?> fb = getFactoryBean(beanName, instance);
        if (bw != null) {
            // 放入缓存
            this.factoryBeanInstanceCache.put(beanName, bw);
        }
        return fb;
    }
}

getNonSingletonFactoryBeanForTypeCheck

不是单例的话,获取FactoryBean,比单例少的步骤是factoryBeanInstanceCache缓冲的操作

private FactoryBean<?> getNonSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
    // 当前线程有在创建
    if (isPrototypeCurrentlyInCreation(beanName)) {
        return null;
    }

    Object instance;
    try {
        // Mark this bean as currently in creation, even if just partially.
        // 标记正在创建
        beforePrototypeCreation(beanName);
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
        // 看看代理能不能返回一个实例
        instance = resolveBeforeInstantiation(beanName, mbd);
        if (instance == null) {
            BeanWrapper bw = createBeanInstance(beanName, mbd, null);
            instance = bw.getWrappedInstance();
        }
    }
    catch (UnsatisfiedDependencyException ex) {
        // Don't swallow, probably misconfiguration...
        throw ex;
    }
    catch (BeanCreationException ex) {
        // Instantiation failure, maybe too early...
        if (logger.isDebugEnabled()) {
            logger.debug("Bean creation exception on non-singleton FactoryBean type check: " + ex);
        }
        onSuppressedException(ex);
        return null;
    }
    finally {
        // Finished partial creation of this bean.
        // 标记创建结束
        afterPrototypeCreation(beanName);
    }
    // 直接转换为FactoryBean
    return getFactoryBean(beanName, instance);
}

applyMergedBeanDefinitionPostProcessors

MergedBeanDefinitionPostProcessor的合并定义

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
        if (bp instanceof MergedBeanDefinitionPostProcessor) {
            MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
            bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
        }
    }
}

resolveBeforeInstantiation

应用实例化前后处理程序,解决指定bean是否有实例化前快捷方式

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
    Object bean = null;
    // 没有明确标明false
    if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
        // Make sure bean class is actually resolved at this point.
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            Class<?> targetType = determineTargetType(beanName, mbd);
            if (targetType != null) {
                // 尝试初始化
                bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                if (bean != null) {
                    bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
            }
        }
        mbd.beforeInstantiationResolved = (bean != null);
    }
    return bean;
}

applyBeanPostProcessorsBeforeInstantiation

尝试初始化

@Nullable
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
        if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
            if (result != null) {
                return result;
            }
        }
    }
    return null;
}

createBeanInstance

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
    // Make sure bean class is actually resolved at this point.
    // 解析beanClass
    Class<?> beanClass = resolveBeanClass(mbd, beanName);

    // 判断是否有类的访问权限
    if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
    }

    // 是否有其他回调
    Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
    if (instanceSupplier != null) {
        return obtainFromSupplier(instanceSupplier, beanName);
    }

    // 是否有工厂方法回调
    if (mbd.getFactoryMethodName() != null) {
        return instantiateUsingFactoryMethod(beanName, mbd, args);
    }

    // Shortcut when re-creating the same bean...
    // 是否解析过
    boolean resolved = false;
    // 为false说明无参,true有参
    boolean autowireNecessary = false;
    if (args == null) {
        synchronized (mbd.constructorArgumentLock) {
            if (mbd.resolvedConstructorOrFactoryMethod != null) {
                resolved = true;
                autowireNecessary = mbd.constructorArgumentsResolved;
            }
        }
    }
    if (resolved) {
        if (autowireNecessary) {
            // 构造器注入
            return autowireConstructor(beanName, mbd, null, null);
        }
        else {
            // 无参构造
            return instantiateBean(beanName, mbd);
        }
    }

    // Candidate constructors for autowiring?
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    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);
}

obtainFromSupplier

从Supplier获取bean

protected BeanWrapper obtainFromSupplier(Supplier<?> instanceSupplier, String beanName) {
    Object instance;
    // 获取原先创建的beanName
    String outerBean = this.currentlyCreatedBean.get();
    // 用当前的替换
    this.currentlyCreatedBean.set(beanName);
    try {
        // 调用Supplier的方法
        instance = instanceSupplier.get();
    }
    finally {
        // 原先的bean存在,设置为原先的
        if (outerBean != null) {
            this.currentlyCreatedBean.set(outerBean);
        }
        // 原先的不存在,就移除,反正原本也为空
        else {
            this.currentlyCreatedBean.remove();
        }
    }
    // 没有创建对象,默认为NullBean
    if (instance == null) {
        instance = new NullBean();
    }
    // 初始化BeanWrapper并返回
    BeanWrapper bw = new BeanWrapperImpl(instance);
    initBeanWrapper(bw);
    return bw;
}

getObjectForBeanInstance

protected Object getObjectForBeanInstance(
        Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
    // 注册当前创建的bean和给定beanName的依赖
    String currentlyCreatedBean = this.currentlyCreatedBean.get();
    if (currentlyCreatedBean != null) {
        registerDependentBean(beanName, currentlyCreatedBean);
    }
    // 返回一个bean
    return super.getObjectForBeanInstance(beanInstance, name, beanName, mbd);
}

determineConstructorsFromBeanPostProcessors

确定bean的构造函数

protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
        throws BeansException {

    if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                // 从SmartInstantiationAwareBeanPostProcessor判断
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
                if (ctors != null) {
                    return ctors;
                }
            }
        }
    }
    return null;
}

instantiateBean

无参构造bean

protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
    try {
        Object beanInstance;
        final BeanFactory parent = this;
        if (System.getSecurityManager() != null) {
            beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
                    getInstantiationStrategy().instantiate(mbd, beanName, parent),
                    getAccessControlContext());
        }
        else {
            // 创建一个bean
            beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
        }
        // 初始化BeanWrapper并返回
        BeanWrapper bw = new BeanWrapperImpl(beanInstance);
        initBeanWrapper(bw);
        return bw;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
}

instantiateUsingFactoryMethod

使用FactoryMethod实例化一个bean

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

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

autowireConstructor

实例化后封装成BeanWrapper

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

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

populateBean

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {  
    if (bw == null) {
        // 如果BeanWrapper为空,但是有属性值,就跑异常
        if (mbd.hasPropertyValues()) {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
        }
        else {
            // Skip property population phase for null instance.
            return;
        }
    }

    // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
    // state of the bean before properties are set. This can be used, for example,
    // to support styles of field injection.
    // 看看InstantiationAwareBeanPostProcessors是否有注入值,如果有注入,就不继续注入,直接返回
    boolean continueWithPropertyPopulation = true;

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

    if (!continueWithPropertyPopulation) {
        return;
    }

    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

    if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
        // 拷贝配置信息
        MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
        // Add property values based on autowire by name if applicable.
        // 根据名称注入
        if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
            autowireByName(beanName, mbd, bw, newPvs);
        }
        // Add property values based on autowire by type if applicable.
        // 根据类型注入
        if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
            autowireByType(beanName, mbd, bw, newPvs);
        }
        pvs = newPvs;
    }
    // r容器是否有InstantiationAwareBeanPostProcessors
    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    // 是否进行依赖检查
    boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

    PropertyDescriptor[] filteredPds = null;
    if (hasInstAwareBpps) {
        if (pvs == null) {
            pvs = mbd.getPropertyValues();
        }
        // 后置处理
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                if (pvsToUse == null) {
                    if (filteredPds == null) {
                        filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                    }
                    pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    if (pvsToUse == null) {
                        return;
                    }
                }
                pvs = pvsToUse;
            }
        }
    }
    if (needsDepCheck) {
        if (filteredPds == null) {
            // 过滤出需要依赖检查的属性
            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        }
        // 检查依赖关系,保证依赖项已初始化
        checkDependencies(beanName, mbd, filteredPds, pvs);
    }

    if (pvs != null) {
        // 此时才开始赋值
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
}

autowireByName

根据名称注入

protected void autowireByName(
        String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    // 获取可set的属性,且这个属性不是简单的属性,比如基本类型、包装类这些
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        // 是否有这个bean
        if (containsBean(propertyName)) {
            // 有的话获取
            Object bean = getBean(propertyName);
            // 添加到pvs
            pvs.add(propertyName, bean);
            // 注册依赖关系
            registerDependentBean(propertyName, beanName);
            if (logger.isTraceEnabled()) {
                logger.trace("Added autowiring by name from bean name '" + beanName +
                        "' via property '" + propertyName + "' to bean named '" + propertyName + "'");
            }
        }
        else {
            if (logger.isTraceEnabled()) {
                logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
                        "' by name: no matching bean found");
            }
        }
    }
}

autowireByType

根据类型注入

protected void autowireByType(
        String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    // 类型转换器获取
    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }

    Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
     // 获取可set的属性,且这个属性不是简单的属性,比如基本类型、包装类这些
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        try {
            PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
            // Don't try autowiring by type for type Object: never makes sense,
            // even if it technically is a unsatisfied, non-simple property.
            // 如果是Object,就不管了
            if (Object.class != pd.getPropertyType()) {
                // 获取写参数
                MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
                // Do not allow eager init for type matching in case of a prioritized post-processor.
                // 是否立即初始化
                boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
                // 依赖描述
                DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
                // 解析依赖
                Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
                if (autowiredArgument != null) {
                    pvs.add(propertyName, autowiredArgument);
                }
                for (String autowiredBeanName : autowiredBeanNames) {
                    // 注册依赖
                    registerDependentBean(autowiredBeanName, beanName);
                    if (logger.isTraceEnabled()) {
                        logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
                                propertyName + "' to bean named '" + autowiredBeanName + "'");
                    }
                }
                autowiredBeanNames.clear();
            }
        }
        catch (BeansException ex) {
            throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
        }
    }
}

unsatisfiedNonSimpleProperties

返回一个不是简单的bean属性数组不包括基本类型或字符串等简单属性。

protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
    Set<String> result = new TreeSet<>();
    PropertyValues pvs = mbd.getPropertyValues();
    PropertyDescriptor[] pds = bw.getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) &&
                !BeanUtils.isSimpleProperty(pd.getPropertyType())) {
            result.add(pd.getName());
        }
    }
    return StringUtils.toStringArray(result);
}

filterPropertyDescriptorsForDependencyCheck

过滤出需要依赖检查的属性

protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw, boolean cache) {
    PropertyDescriptor[] filtered = this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass());
    if (filtered == null) {
        filtered = filterPropertyDescriptorsForDependencyCheck(bw);
        // 缓存
        if (cache) {
            PropertyDescriptor[] existing =
                    this.filteredPropertyDescriptorsCache.putIfAbsent(bw.getWrappedClass(), filtered);
            if (existing != null) {
                filtered = existing;
            }
        }
    }
    return filtered;
}
protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw) {
    List<PropertyDescriptor> pds = new ArrayList<>(Arrays.asList(bw.getPropertyDescriptors()));
    pds.removeIf(this::isExcludedFromDependencyCheck);
    return pds.toArray(new PropertyDescriptor[0]);
}

isExcludedFromDependencyCheck

指定的bean属性是否被排除在依赖项检查之外。

protected boolean isExcludedFromDependencyCheck(PropertyDescriptor pd) {
    return (AutowireUtils.isExcludedFromDependencyCheck(pd) ||
            this.ignoredDependencyTypes.contains(pd.getPropertyType()) ||
            AutowireUtils.isSetterDefinedInInterface(pd, this.ignoredDependencyInterfaces));
}

checkDependencies

检查依赖项是否是公开的

protected void checkDependencies(
        String beanName, AbstractBeanDefinition mbd, PropertyDescriptor[] pds, @Nullable PropertyValues pvs)
        throws UnsatisfiedDependencyException {

    int dependencyCheck = mbd.getDependencyCheck();
    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() != null && (pvs == null || !pvs.contains(pd.getName()))) {
            boolean isSimple = BeanUtils.isSimpleProperty(pd.getPropertyType());
            boolean unsatisfied = (dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_ALL) ||
                    (isSimple && dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_SIMPLE) ||
                    (!isSimple && dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
            if (unsatisfied) {
                throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, pd.getName(),
                        "Set this property value or disable dependency checking for this bean.");
            }
        }
    }
}

applyPropertyValues

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    // 为空直接返回
    if (pvs.isEmpty()) {
        return;
    }

    if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
        ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
    }

    MutablePropertyValues mpvs = null;
    List<PropertyValue> original;

    if (pvs instanceof MutablePropertyValues) {
        mpvs = (MutablePropertyValues) pvs;
        if (mpvs.isConverted()) {
            // Shortcut: use the pre-converted values as-is.
            try {
                // 已完成,直接返回
                bw.setPropertyValues(mpvs);
                return;
            }
            catch (BeansException ex) {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Error setting property values", ex);
            }
        }
        original = mpvs.getPropertyValueList();
    }
    else {
        original = Arrays.asList(pvs.getPropertyValues());
    }

    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }
    // bean定义解析器
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

    // Create a deep copy, resolving any references for values.
    List<PropertyValue> deepCopy = new ArrayList<>(original.size());
    boolean resolveNecessary = false;
    // 对original的深度复制,已解析的直接加到deepCopy,没解析的先解析,再加入到deepCopy
    for (PropertyValue pv : original) {
        // 已解析
        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 = convertForProperty(resolvedValue, propertyName, bw, converter);
            }
            // Possibly store converted value in merged bean definition,
            // in order to avoid re-conversion for every created bean instance.
            // 解析值和原值一样
            if (resolvedValue == originalValue) {
                // 避免重复转换
                if (convertible) {
                    pv.setConvertedValue(convertedValue);
                }
                deepCopy.add(pv);
            }
            else if (convertible && originalValue instanceof TypedStringValue &&
                    !((TypedStringValue) originalValue).isDynamic() &&
                    !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
                pv.setConvertedValue(convertedValue);
                deepCopy.add(pv);
            }
            else {
                resolveNecessary = true;
                deepCopy.add(new PropertyValue(pv, convertedValue));
            }
        }
    }
    if (mpvs != null && !resolveNecessary) {
        mpvs.setConverted();
    }

    // Set our (possibly massaged) deep copy.
    try {
        // 设值
        bw.setPropertyValues(new MutablePropertyValues(deepCopy));
    }
    catch (BeansException ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Error setting property values", ex);
    }
}

convertForProperty

转换值initializeBean

private Object convertForProperty(
        @Nullable Object value, String propertyName, BeanWrapper bw, TypeConverter converter) {

    if (converter instanceof BeanWrapperImpl) {
        return ((BeanWrapperImpl) converter).convertForProperty(value, propertyName);
    }
    else {
        PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
        MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
        return converter.convertIfNecessary(value, pd.getPropertyType(), methodParam);
    }
}

invokeInitMethods

protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
        throws Throwable {

    boolean isInitializingBean = (bean instanceof InitializingBean);
    // 如果是InitializingBean并且有afterPropertiesSet,调用afterPropertiesSet方法
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (logger.isTraceEnabled()) {
            logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }
        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                    ((InitializingBean) bean).afterPropertiesSet();
                    return null;
                }, getAccessControlContext());
            }
            catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        }
        else {
            ((InitializingBean) bean).afterPropertiesSet();
        }
    }
    // 如果是InitializingBean,但没有afterPropertiesSet,调用自定义的方法
    if (mbd != null && bean.getClass() != NullBean.class) {
        String initMethodName = mbd.getInitMethodName();
        if (StringUtils.hasLength(initMethodName) &&
                !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                !mbd.isExternallyManagedInitMethod(initMethodName)) {
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}

invokeCustomInitMethod

protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
        throws Throwable {
    // 获取初始化方法名称
    String initMethodName = mbd.getInitMethodName();
    Assert.state(initMethodName != null, "No init method set");
    // 获取初始化方法
    final Method initMethod = (mbd.isNonPublicAccessAllowed() ?
            BeanUtils.findMethod(bean.getClass(), initMethodName) :
            ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));

    if (initMethod == null) {
        if (mbd.isEnforceInitMethod()) {
            throw new BeanDefinitionValidationException("Could not find an init method named '" +
                    initMethodName + "' on bean with name '" + beanName + "'");
        }
        else {
            if (logger.isTraceEnabled()) {
                logger.trace("No default init method named '" + initMethodName +
                        "' found on bean with name '" + beanName + "'");
            }
            // Ignore non-existent default lifecycle methods.
            return;
        }
    }

    if (logger.isTraceEnabled()) {
        logger.trace("Invoking init method  '" + initMethodName + "' on bean with name '" + beanName + "'");
    }

    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            ReflectionUtils.makeAccessible(initMethod);
            return null;
        });
        try {
            AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () ->
                initMethod.invoke(bean), getAccessControlContext());
        }
        catch (PrivilegedActionException pae) {
            InvocationTargetException ex = (InvocationTargetException) pae.getException();
            throw ex.getTargetException();
        }
    }
    else {
        try {
            // 给权限
            ReflectionUtils.makeAccessible(initMethod);
            // 反射
            initMethod.invoke(bean);
        }
        catch (InvocationTargetException ex) {
            throw ex.getTargetException();
        }
    }
}

postProcessObjectFromFactoryBean

调用后置处理器

protected Object postProcessObjectFromFactoryBean(Object object, String beanName) {
    return applyBeanPostProcessorsAfterInitialization(object, beanName);
}

removeSingleton

移除单例,这边额外多了factoryBeanInstanceCache缓存

protected void removeSingleton(String beanName) {
    synchronized (getSingletonMutex()) {
        super.removeSingleton(beanName);
        this.factoryBeanInstanceCache.remove(beanName);
    }
}

clearSingletonCache

清空单例,这边额外多了factoryBeanInstanceCache缓存

protected void clearSingletonCache() {
    synchronized (getSingletonMutex()) {
        super.clearSingletonCache();
        this.factoryBeanInstanceCache.clear();
    }
}

getLogger

获取logger

Log getLogger() {
    return logger;
}

原文 

https://segmentfault.com/a/1190000020967964

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。

PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » spring学习之源码分析–AbstractAutowireCapableBeanFactory

赞 (0)
分享到:更多 ()

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址