Spring源码解析之bean的创建

阅读须知

  • Spring源码版本:4.3.8
  • 文章中使用/* */注释的方法会做深入分析

正文

之前我们都是在围绕

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");

这句代码来分析Spring在初始化过程中都做了哪些工作,其中bean创建的部分我们并没有做深入分析,这篇文章我们就来分析一下Spring在创建bean的过程中都做了哪些工作,围绕这句代码来分析:

A a = applicationContext .getBean(A.class);

getBean这个方法有多种重载的形式,但最终都会调用doGetBean方法来创建bean,我们就以这个方法作为入口来分析:
AbstractBeanFactory:

protected <T> T doGetBean(
        final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
        throws BeansException {
    final String beanName = transformedBeanName(name);
    Object bean;
    /* 尝试从缓存中获取单例bean */
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) {
        if (logger.isDebugEnabled()) {
            if (isSingletonCurrentlyInCreation(beanName)) {
                logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
                        "' that is not fully initialized yet - a consequence of a circular reference");
            }
            else {
                logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
            }
        }
        /* 如果是工厂类型的bean,要调用相关工厂方法获取bean */
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }
    else {
        // 原型模式的循环依赖无法解决,抛出异常
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }
        BeanFactory parentBeanFactory = getParentBeanFactory();
        // 检查当前BeanFactory中是否包含当前待创建的bean的BeanDefinition,如果不存在,则递归尝试从父级的BeanFactory加载
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            String nameToLookup = originalBeanName(name);
            if (args != null) {
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            }
            else {
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
        }
        if (!typeCheckOnly) {
            /* 如果创建bean不是为了类型检查,则要标记当前bean已经被创建或者即将被创建以便于BeanFactory可以优化重复创建的bean的缓存 */
            markBeanAsCreated(beanName);
        }
        try {
            /* 合并父BeanDefinition */
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            checkMergedBeanDefinition(mbd, beanName, args);
            String[] dependsOn = mbd.getDependsOn(); // 依赖的bean
            if (dependsOn != null) {
                for (String dep : dependsOn) {
                    if (isDependent(beanName, dep)) { // 循环依赖检查
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                    }
                    // 将依赖的关系放入缓存,以便于当前bean销毁时先销毁依赖的bean
                    registerDependentBean(dep, beanName);
                    getBean(dep); // 创建依赖的bean
                }
            }
            if (mbd.isSingleton()) {
                /* 尝试从缓存中加载单例bean */
                sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
                    @Override
                    public Object getObject() throws BeansException {
                        try {
                            /* 创建bean */
                            return createBean(beanName, mbd, args);
                        }
                        catch (BeansException ex) {
                            destroySingleton(beanName);
                            throw ex;
                        }
                    }
                });
                /* 同样的工厂类型的bean的处理 */
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            }
            else if (mbd.isPrototype()) {
                Object prototypeInstance = null;
                try {
                    // 原型模式bean创建前置处理,默认情况下记录当前bean正在创建
                    beforePrototypeCreation(beanName);
                    /* 创建bean */
                    prototypeInstance = createBean(beanName, mbd, args);
                }
                finally {
                    // 原型模式bean创建后置处理,默认情况下移除当前bean正在创建的记录,也就是当前bean已经创建完成
                    afterPrototypeCreation(beanName);
                }
                /* 同样的工厂类型的bean的处理 */
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            }
            else { // 其他scope类型的处理
                String scopeName = mbd.getScope();
                final Scope scope = this.scopes.get(scopeName);
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                }
                try {
                    Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
                        @Override
                        public Object getObject() throws BeansException {
                            beforePrototypeCreation(beanName); // 前置处理
                            try {
                                return createBean(beanName, mbd, args); /* 创建bean */
                            }
                            finally {
                                afterPrototypeCreation(beanName); // 后置处理
                            }
                        }
                    });
                    /* 同样的工厂类型的bean的处理 */
                    bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                }
                catch (IllegalStateException ex) {
                    throw new BeanCreationException(beanName,
                            "Scope '" + scopeName + "' is not active for the current thread; consider " +
                            "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                            ex);
                }
            }
        }
        catch (BeansException ex) {
            cleanupAfterBeanCreationFailure(beanName);
            throw ex;
        }
    }
    if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
        try {
            // 如果需要,使用类型转换器装换类型
            return getTypeConverter().convertIfNecessary(bean, requiredType);
        }
        catch (TypeMismatchException ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Failed to convert bean '" + name + "' to required type '" +
                        ClassUtils.getQualifiedName(requiredType) + "'", ex);
            }
            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
        }
    }
    return (T) bean;
}

DefaultSingletonBeanRegistry:

public Object getSingleton(String beanName) {
    /* 尝试从缓存中获取,true为允许提前依赖 */
    return getSingleton(beanName, true);
}

DefaultSingletonBeanRegistry:

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    Object singletonObject = this.singletonObjects.get(beanName); // 首先尝试从缓存中获取单例bean
    // 如果缓存中为空并且bean正在创建中
    if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
        synchronized (this.singletonObjects) {
            /* 从提前加载的bean的缓存集合中获取 */
            singletonObject = this.earlySingletonObjects.get(beanName);
            // 如果为空并且允许提前依赖
            if (singletonObject == null && allowEarlyReference) {
                // 从缓存中获取bean的工厂
                ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                if (singletonFactory != null) {
                    // 如果工厂不为空则调用工厂方法加载bean
                    singletonObject = singletonFactory.getObject();
                    // 记录到提前加载的bean的缓存中
                    this.earlySingletonObjects.put(beanName, singletonObject);
                    // 已经调用工厂加载bean,将工厂从缓存中移除,无需再次加载
                    this.singletonFactories.remove(beanName);
                }
            }
        }
    }
    return (singletonObject != NULL_OBJECT ? singletonObject : null);
}

AbstractBeanFactory:

protected Object getObjectForBeanInstance(
        Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {
    // 如果beanName以&符开头(代表要获取FactoryBean本身)但类型不是FactoryBean抛出异常
    if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
        throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
    }
    // 如果bean不是FactoryBean或者要获取FactoryBean本身而不是要获取工厂方法返回的实例则直接返回bean实例
    if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
        return beanInstance;
    }
    // 过了上两步的判断到这里可以确定当前bean一定是FactoryBean
    Object object = null;
    if (mbd == null) {
        // 尝试从缓存中获取FactoryBean
        object = getCachedObjectForFactoryBean(beanName);
    }
    if (object == null) {
        FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
        if (mbd == null && containsBeanDefinition(beanName)) {
            /* 合并父BeanDefinition */
            mbd = getMergedLocalBeanDefinition(beanName);
        }
        // 是否是用户自定义的而不是应用程序本身定义的
        boolean synthetic = (mbd != null && mbd.isSynthetic());
        /* 从FactoryBean中加载bean */
        object = getObjectFromFactoryBean(factory, beanName, !synthetic);
    }
    return object;
}

AbstractBeanFactory:

protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
    // 如果已经合并过,直接返回
    RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
    if (mbd != null) {
        return mbd;
    }
    return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}

AbstractBeanFactory:

protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
        throws BeanDefinitionStoreException {
    return getMergedBeanDefinition(beanName, bd, null);
}

AbstractBeanFactory:

protected RootBeanDefinition getMergedBeanDefinition(
        String beanName, BeanDefinition bd, BeanDefinition containingBd)
        throws BeanDefinitionStoreException {
    synchronized (this.mergedBeanDefinitions) {
        RootBeanDefinition mbd = null;
        if (containingBd == null) {
            // 锁定全局缓存后双重检查是否已经合并过,避免重复合并
            mbd = this.mergedBeanDefinitions.get(beanName);
        }
        if (mbd == null) {
            if (bd.getParentName() == null) {
                // 如果没有父BeanDefinition,直接转换成RootBeanDefinition返回
                if (bd instanceof RootBeanDefinition) {
                    mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
                }
                else {
                    mbd = new RootBeanDefinition(bd);
                }
            }
            else {
                BeanDefinition pbd;
                try {
                    // 转换父beanName,主要处理FactoryBean的&符合alias别名
                    String parentBeanName = transformedBeanName(bd.getParentName());
                    if (!beanName.equals(parentBeanName)) {
                        /* 递归合并父BeanDefinition */
                        pbd = getMergedBeanDefinition(parentBeanName);
                    }
                    else {
                        // 如果当前bean和父bean的name相同,则尝试用父BeanFactory递归合并
                        BeanFactory parent = getParentBeanFactory();
                        if (parent instanceof ConfigurableBeanFactory) {
                            pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
                        }
                        else {
                            throw new NoSuchBeanDefinitionException(parentBeanName,
                                    "Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
                                    "': cannot be resolved without an AbstractBeanFactory parent");
                        }
                    }
                }
                catch (NoSuchBeanDefinitionException ex) {
                    throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
                            "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
                }
                mbd = new RootBeanDefinition(pbd);
                mbd.overrideFrom(bd); // 深复制父BeanDefinition,将属性copy一遍
            }
            if (!StringUtils.hasLength(mbd.getScope())) {
                mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON); // 设置默认scope
            }
            // 如果当前bean是内部bean并且scope为默认的单例,则要将scope设置为外部bean相同
            if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
                mbd.setScope(containingBd.getScope());
            }
            if (containingBd == null && isCacheBeanMetadata()) {
                // 放入缓存代表已经合并过
                this.mergedBeanDefinitions.put(beanName, mbd);
            }
        }
        return mbd;
    }
}

AbstractBeanFactory:

public BeanDefinition getMergedBeanDefinition(String name) throws BeansException {
    String beanName = transformedBeanName(name); // 转换beanName
    // 如果当前BeanFactory中不包含当前BeanDefinition,则尝试从父BeanFactory中递归合并
    if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
        return ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(beanName);
    } 
    // 递归合并父BeanDefinition
    return getMergedLocalBeanDefinition(beanName);
}

FactoryBeanRegistrySupport:

protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
    if (factory.isSingleton() && containsSingleton(beanName)) { // 单例
        synchronized (getSingletonMutex()) {
            Object object = this.factoryBeanObjectCache.get(beanName); // 尝试从缓存中获取FactoryBean
            if (object == null) {
                /* 从FactoryBean中加载bean */
                object = doGetObjectFromFactoryBean(factory, beanName);
                Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
                // 这里再次尝试从缓存中获取是因为自定义的bean调用处理循环依赖时可能已经放入缓存
                if (alreadyThere != null) {
                    object = alreadyThere;
                }
                else {
                    if (object != null && shouldPostProcess) {
                        try {
                            /* BeanPostProcessor的调用 */
                            object = postProcessObjectFromFactoryBean(object, beanName);
                        }
                        catch (Throwable ex) {
                            throw new BeanCreationException(beanName,
                                    "Post-processing of FactoryBean's singleton object failed", ex);
                        }
                    }
                    this.factoryBeanObjectCache.put(beanName, (object != null ? object : NULL_OBJECT)); // 将FactoryBean放入缓存
                }
            }
            return (object != NULL_OBJECT ? object : null);
        }
    }
    else { // 非单例
        /* 从FactoryBean中加载bean */
        Object object = doGetObjectFromFactoryBean(factory, beanName);
        if (object != null && shouldPostProcess) {
            try {
                /* BeanPostProcessor的调用 */
                object = postProcessObjectFromFactoryBean(object, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
            }
        }
        return object;
    }
}

FactoryBeanRegistrySupport:

private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName)
        throws BeanCreationException {
    Object object;
    try {
        if (System.getSecurityManager() != null) {
            AccessControlContext acc = getAccessControlContext();
            try {
                object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                    @Override
                    public Object run() throws Exception {
                            // 调用getObject方法获取bean
                            return factory.getObject();
                        }
                    }, acc);
            }
            catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        }
        else {
            object = factory.getObject(); // 调用getObject方法获取bean
        }
    }
    catch (FactoryBeanNotInitializedException ex) {
        throw new BeanCurrentlyInCreationException(beanName, ex.toString());
    }
    catch (Throwable ex) {
        throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
    }
    if (object == null && isSingletonCurrentlyInCreation(beanName)) {
        throw new BeanCurrentlyInCreationException(
                beanName, "FactoryBean which is currently in creation returned null from getObject");
    }
    return object;
}

方法的内容很明确,就是调用getObject方法来获取bean。下面就是BeanPostProcessor的调用,关于BeanPostProcessor,我们在之前的文章说描述过它的作用,笔者也会在后续的文章中介绍它的典型应用,AOP和事务等。
AbstractAutowireCapableBeanFactory:

protected Object postProcessObjectFromFactoryBean(Object object, String beanName) {
    /* 调用BeanPostProcessor */
    return applyBeanPostProcessorsAfterInitialization(object, beanName);
}

AbstractAutowireCapableBeanFactory:

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
        throws BeansException {
    Object result = existingBean;
    for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
        result = beanProcessor.postProcessAfterInitialization(result, beanName);
        if (result == null) {
            return result;
        }
    }
    return result;
}

我们在之前的文章中讲述过BeanPostProcessor的注册,而这里就会将这些注册的BeanPostProcessor取出遍历调用它们的postProcessAfterInitialization方法。现在我们回到加载bean的主流程中去:
AbstractBeanFactory:

protected void markBeanAsCreated(String beanName) {
    if (!this.alreadyCreated.contains(beanName)) {
        synchronized (this.mergedBeanDefinitions) {
            if (!this.alreadyCreated.contains(beanName)) {
                // 在创建bean期间有可能有一些元数据的变化,这里清除合并缓存让BeanDefinition可以重新合并
                clearMergedBeanDefinition(beanName);
                this.alreadyCreated.add(beanName);
            }
        }
    }
}

我们在标签解析的文章中分析BeanDefinition的注册时,曾经看到过Spring用hasBeanCreationStarted方法来判断bean的创建是否已经开始,而判断的依据alreadyCreated集合就是在这里放置元素的。下面是单例bean的加载:
DefaultSingletonBeanRegistry:

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
    Assert.notNull(beanName, "'beanName' must not be null");
    synchronized (this.singletonObjects) {
        Object singletonObject = this.singletonObjects.get(beanName); // 尝试从缓存中获取
        if (singletonObject == null) {
            // 如果bean正在销毁抛出异常
            if (this.singletonsCurrentlyInDestruction) {
                throw new BeanCreationNotAllowedException(beanName,
                        "Singleton bean creation not allowed while singletons of this factory are in destruction " +
                        "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
            }
            /* 单例bean创建前置处理 */
            beforeSingletonCreation(beanName);
            boolean newSingleton = false;
            boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
            if (recordSuppressedExceptions) {
                this.suppressedExceptions = new LinkedHashSet<Exception>();
            }
            try {
                /* 调用getObject方法获取bean */
                singletonObject = singletonFactory.getObject();
                newSingleton = true;
            }
            catch (IllegalStateException ex) {
                singletonObject = this.singletonObjects.get(beanName);
                if (singletonObject == null) {
                    throw ex;
                }
            }
            catch (BeanCreationException ex) {
                if (recordSuppressedExceptions) {
                    for (Exception suppressedException : this.suppressedExceptions) {
                        ex.addRelatedCause(suppressedException);
                    }
                }
                throw ex;
            }
            finally {
                if (recordSuppressedExceptions) {
                    this.suppressedExceptions = null;
                }
                /* 单例bean创建后置处理 */
                afterSingletonCreation(beanName);
            }
            if (newSingleton) {
                /* 添加到缓存中 */
                addSingleton(beanName, singletonObject);
            }
        }
        return (singletonObject != NULL_OBJECT ? singletonObject : null);
    }
}

DefaultSingletonBeanRegistry:

protected void beforeSingletonCreation(String beanName) {
    if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
        throw new BeanCurrentlyInCreationException(beanName);
    }
}

默认的前置处理就是将beanName放入了singletonsCurrentlyInCreation集合中,代表bean正在创建中,而这个集合就是Spring解决循环依赖的关键,后面我们会说到。默认的后置处理就是将beanName从这个集合中移除掉,代表bean已经创建完成:

DefaultSingletonBeanRegistry:

protected void afterSingletonCreation(String beanName) {
    if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
        throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
    }
}

DefaultSingletonBeanRegistry:

protected void addSingleton(String beanName, Object singletonObject) {
    synchronized (this.singletonObjects) {
        // 写入单例bean缓存
        this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
        this.singletonFactories.remove(beanName); // 工厂缓存移除掉,bean创建完成工厂就没用了
        this.earlySingletonObjects.remove(beanName); // 提前创建的bean的标记移除掉
        this.registeredSingletons.add(beanName); // 将beanName放入已经注册的单例bean的缓存
    }
}

添加缓存就是对各个相关的缓存的处理。下面我们来分析getObject方法获取bean的过程,这里的ObjectFactory参数是在调用时new的一个匿名内部类,而它的getObject方法中调用了createBean方法,我们来分析这个方法:
AbstractAutowireCapableBeanFactory:

protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating instance of bean '" + beanName + "'");
    }
    RootBeanDefinition mbdToUse = mbd;
    // 锁定class,根据设置的class属性或者className来解析class
    Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
        mbdToUse = new RootBeanDefinition(mbd); // 克隆BeanDefinition
        mbdToUse.setBeanClass(resolvedClass);
    }
    try {
        /* 验证以及准备覆盖的方法 */
        mbdToUse.prepareMethodOverrides();
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                beanName, "Validation of method overrides failed", ex);
    }
    try {
        /* 给BeanPostProcessors一个机会返回一个代理来替代目标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);
    }
    /* 创建bean */
    Object beanInstance = doCreateBean(beanName, mbdToUse, args);
    if (logger.isDebugEnabled()) {
        logger.debug("Finished creating instance of bean '" + beanName + "'");
    }
    return beanInstance;
}

AbstractBeanDefinition:

public void prepareMethodOverrides() throws BeanDefinitionValidationException {
    MethodOverrides methodOverrides = getMethodOverrides();
    if (!methodOverrides.isEmpty()) {
        Set<MethodOverride> overrides = methodOverrides.getOverrides();
        synchronized (overrides) {
            for (MethodOverride mo : overrides) {
                /* 准备方法覆盖 */
                prepareMethodOverride(mo);
            }
        }
    }
}

AbstractBeanDefinition:

protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException {
    int count = ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName()); // 根据方法名获取方法的数量
    if (count == 0) { // 如果方法不存在则抛出异常
        throw new BeanDefinitionValidationException(
                "Invalid method override: no method with name '" + mo.getMethodName() +
                "' on class [" + getBeanClassName() + "]");
    }
    else if (count == 1) {
        // 如果方法数量为1说明不存在重载方法,将方法重载设置false来避免类型检查的开销
        mo.setOverloaded(false);
    }
}

关于MethodOverride,我们在Spring标签解析的文章中分析lookup-method和replace-method两个配置的解析时,发现这两个配置的加载其实就是将配置统一存放在BeanDefinition的methodOverrides属性中,关于MethodOverride的应用我们后面会详细介绍,这里提前判断的方法是否存在和方法的数量,确定是否有重载方法,如果没有重载方法后面就不需要做参数的匹配了。
AbstractAutowireCapableBeanFactory:

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
    Object bean = null;
    if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            // 解析class,包括从工厂中获取目标bean的class的处理
            Class<?> targetType = determineTargetType(beanName, mbd);
            if (targetType != null) {
                /* bean实例化前BeanPostProcessor的调用,在这里当前bean可能会被代理替代 */
                bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                if (bean != null) {
                    /* 如果在上一步处理过后bean不为null,则在这里应用BeanPostProcessor的后置处理 */
                    bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
            }
        }
        mbd.beforeInstantiationResolved = (bean != null);
    }
    return bean;
}

AbstractAutowireCapableBeanFactory:

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

BeanPostProcessor的后置处理我们在上文中分析FactoryBean的处理时已经提到过,这里不再重复。
AbstractAutowireCapableBeanFactory:

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
        throws BeanCreationException {
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        /* 创建bean实例 */
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
    Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
    mbd.resolvedTargetType = beanType;
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                // 允许MergedBeanDefinitionPostProcessor修改合并的BeanDefinition
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }
    // 解决循环依赖,是否提前曝光,单例并且允许循环依赖并且bean正在创建中
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
            isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
        if (logger.isDebugEnabled()) {
            logger.debug("Eagerly caching bean '" + beanName +
                    "' to allow for resolving potential circular references");
        }
        /* 解决循环依赖,在bean初始化完成之前将创建bean的工厂加入到缓存中 */
        addSingletonFactory(beanName, new ObjectFactory<Object>() {
            @Override
            public Object getObject() throws BeansException {
                // 应用SmartInstantiationAwareBeanPostProcessor,获取被提前访问的bean的引用,通常用于处理循环依赖
                return getEarlyBeanReference(beanName, mbd, bean);
            }
        });
    }
    Object exposedObject = bean;
    try {
        /* 对bean进行填充,将各个属性值注入,属性值的注入可能依赖其他bean,则会递归初始化依赖的bean */
        populateBean(beanName, mbd, instanceWrapper);
        if (exposedObject != null) {
            /* 调用初始化方法 */
            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);
        // 如果earlySingletonReference不为空,说明检测到循环依赖
        if (earlySingletonReference != null) {
            // 相等说明bean没有被改变过,也就是没有被代理
            if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
            }
            else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                String[] dependentBeans = getDependentBeans(beanName);
                Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                    // 判断依赖的bean是否创建完成
                    if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                        actualDependentBeans.add(dependentBean);
                    }
                }
                // 不为空表示当前bean创建后依赖的bean并没有全部创建完成,抛出异常
                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 */
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }
    return exposedObject;
}

这里提到了Spring的循环依赖,简单说明一下,首先Spring只能解决单例bean的循环依赖,非单例的循环依赖会抛出异常。对于单例bean的循环依赖,只能解决setter方式的注入依赖,解决的方式上面提到过,就是通过提前暴露一个单例工厂从而使其他bean能引用到该bean。构造方法方式的循环依赖无法解决同样会抛出异常。
AbstractAutowireCapableBeanFactory:

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
    // 解析class
    Class<?> beanClass = resolveBeanClass(mbd, beanName);
    // bean的class访问修饰符和非public方法访问权限的判断
    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());
    }
    if (mbd.getFactoryMethodName() != null)  {
        // 如果工厂方法不为空则使用工厂方法来初始化bean,下文会讲解构造方法实例化bean的方式,使用工厂方法实例化bean的方式和构造方法实例化bean的方式非常类似,不再单独阐述
        return instantiateUsingFactoryMethod(beanName, mbd, args);
    }
    boolean resolved = false;
    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);
        }
    }
    /* 根据参数匹配构造方法 */
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null ||
            mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
            mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
        /* 构造函数自动注入 */
        return autowireConstructor(beanName, mbd, ctors, args);
    }
    /* 使用默认无参构造方法进行初始化 */
    return instantiateBean(beanName, mbd);
}

AbstractAutowireCapableBeanFactory:

protected BeanWrapper autowireConstructor(
        String beanName, RootBeanDefinition mbd, Constructor<?>[] ctors, Object[] explicitArgs) {
    /* 构造方法自动注入 */
    return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
}

ConstructorResolver:

public BeanWrapper autowireConstructor(final String beanName, final RootBeanDefinition mbd,
        Constructor<?>[] chosenCtors, final Object[] explicitArgs) {
    BeanWrapperImpl bw = new BeanWrapperImpl();
    // 初始化BeanWrapper,主要为其织入PropertyEditor属性编辑器
    this.beanFactory.initBeanWrapper(bw);
    Constructor<?> constructorToUse = null;
    ArgumentsHolder argsHolderToUse = null;
    Object[] argsToUse = null;
    if (explicitArgs != null) {
        // 如果传入了参数列表,则使用传入的参数进行匹配
        argsToUse = explicitArgs;
    }
    else {
        Object[] argsToResolve = null;
        synchronized (mbd.constructorArgumentLock) {
            constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
            if (constructorToUse != null && mbd.constructorArgumentsResolved) {
                // 尝试从缓存中获取
                argsToUse = mbd.resolvedConstructorArguments;
                if (argsToUse == null) {
                    // 用户配置的构造方法的参数
                    argsToResolve = mbd.preparedConstructorArguments;
                }
            }
        }
        if (argsToResolve != null) { // 缓存中存在
            // 解析参数列表,包括类型转换和应用用户自定义的TypeConverter类型转换器等
            argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
        }
    }
    if (constructorToUse == null) {
        boolean autowiring = (chosenCtors != null ||
                mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
        ConstructorArgumentValues resolvedValues = null;
        int minNrOfArgs;
        if (explicitArgs != null) { // 传入了参数列表
            minNrOfArgs = explicitArgs.length;
        }
        else {
            // 没有传入获取配置文件中配置的构造方法的参数列表(解析constructor-arg标签时为BeanDefinition设置的属性)
            ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
            // 用于保存解析后的构造参数的值
            resolvedValues = new ConstructorArgumentValues();
            // 解析参数返回个数
            minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
        }
        Constructor<?>[] candidates = chosenCtors;
        if (candidates == null) {
            Class<?> beanClass = mbd.getBeanClass();
            try {
                // 获取类的构造方法数组
                candidates = (mbd.isNonPublicAccessAllowed() ?
                        beanClass.getDeclaredConstructors() : beanClass.getConstructors());
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Resolution of declared constructors on bean Class [" + beanClass.getName() +
                        "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
            }
        }
        // 排序,public优先,参数数量降序
        AutowireUtils.sortConstructors(candidates);
        int minTypeDiffWeight = Integer.MAX_VALUE;
        Set<Constructor<?>> ambiguousConstructors = null;
        LinkedList<UnsatisfiedDependencyException> causes = null;
        for (Constructor<?> candidate : candidates) {
            Class<?>[] paramTypes = candidate.getParameterTypes();
            if (constructorToUse != null && argsToUse.length > paramTypes.length) {
                // 如果已经找到了选用的构造方法并且使用的参数列表的长度大于当前遍历的构造方法的参数列表的长度,直接退出,因为已经按照参数长度进行降序排序了,后续遍历的构造方法也不会匹配
                break;
            }
            if (paramTypes.length < minNrOfArgs) {
                // 相反如果小于就继续遍历寻找参数个数相等的
                continue;
            }
            ArgumentsHolder argsHolder;
            if (resolvedValues != null) { // 如果配置的参数不为空
                try {
                    // 首先尝试从@ConstructorProperties注解上获取参数名称
                    String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length);
                    if (paramNames == null) {
                        ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                        if (pnd != null) {
                            // DefaultParameterNameDiscoverer参数名称发现器用反射的方式获取参数的名称
                            paramNames = pnd.getParameterNames(candidate);
                        }
                    }
                    /* 创建参数数组 */
                    argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
                            getUserDeclaredConstructor(candidate), autowiring);
                }
                catch (UnsatisfiedDependencyException ex) {
                    if (this.beanFactory.logger.isTraceEnabled()) {
                        this.beanFactory.logger.trace(
                                "Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
                    }
                    if (causes == null) {
                        causes = new LinkedList<UnsatisfiedDependencyException>();
                    }
                    causes.add(ex);
                    continue;
                }
            }
            else {
                // 有明确的参数给出的情况,参数列表长度必须一致
                if (paramTypes.length != explicitArgs.length) {
                    continue;
                }
                argsHolder = new ArgumentsHolder(explicitArgs);
            }
            // 获取参数匹配的权重,值越小越匹配
            int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
                    argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
            // 如果当前匹配度较高,将本次遍历解析出的参数和构造方法赋值给目前选中的相关参数,下一轮遍历继续比较
            if (typeDiffWeight < minTypeDiffWeight) {
                constructorToUse = candidate;
                argsHolderToUse = argsHolder;
                argsToUse = argsHolder.arguments;
                minTypeDiffWeight = typeDiffWeight;
                ambiguousConstructors = null;
            }
            else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
                if (ambiguousConstructors == null) {
                    ambiguousConstructors = new LinkedHashSet<Constructor<?>>();
                    ambiguousConstructors.add(constructorToUse);
                }
                ambiguousConstructors.add(candidate);
            }
        }
        if (constructorToUse == null) { // 构造方法遍历结束还是没有匹配成功,抛出异常
            if (causes != null) {
                UnsatisfiedDependencyException ex = causes.removeLast();
                for (Exception cause : causes) {
                    this.beanFactory.onSuppressedException(cause);
                }
                throw ex;
            }
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Could not resolve matching constructor " +
                    "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
        }
        else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Ambiguous constructor matches found in bean '" + beanName + "' " +
                    "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
                    ambiguousConstructors);
        }
        if (explicitArgs == null) {
            // 将解析的构造方法和参数加入缓存
            argsHolderToUse.storeCache(mbd, constructorToUse);
        }
    }
    try {
        Object beanInstance;
        if (System.getSecurityManager() != null) {
            final Constructor<?> ctorToUse = constructorToUse;
            final Object[] argumentsToUse = argsToUse;
            beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    /* 根据选中的构造方法实例化bean */
                    return beanFactory.getInstantiationStrategy().instantiate(
                            mbd, beanName, beanFactory, ctorToUse, argumentsToUse);
                }
            }, beanFactory.getAccessControlContext());
        }
        else {
            /* 根据选中的构造方法实例化bean */
            beanInstance = this.beanFactory.getInstantiationStrategy().instantiate(
                    mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
        }
        // 放入包装类返回
        bw.setBeanInstance(beanInstance);
        return bw;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Bean instantiation via constructor failed", ex);
    }
}

ConstructorResolver:

private ArgumentsHolder createArgumentArray(
        String beanName, RootBeanDefinition mbd, ConstructorArgumentValues resolvedValues,
        BeanWrapper bw, Class<?>[] paramTypes, String[] paramNames, Object methodOrCtor,
        boolean autowiring) throws UnsatisfiedDependencyException {
    // 如果有自定义类型转换器,则应用
    TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
    TypeConverter converter = (customConverter != null ? customConverter : bw);
    ArgumentsHolder args = new ArgumentsHolder(paramTypes.length);
    Set<ConstructorArgumentValues.ValueHolder> usedValueHolders =
            new HashSet<ConstructorArgumentValues.ValueHolder>(paramTypes.length);
    Set<String> autowiredBeanNames = new LinkedHashSet<String>(4);
    for (int paramIndex = 0; paramIndex < paramTypes.length; paramIndex++) {
        Class<?> paramType = paramTypes[paramIndex];
        String paramName = (paramNames != null ? paramNames[paramIndex] : "");
        // 首先尝试通过index获取value,没有再通过类型匹配的方式获取value
        ConstructorArgumentValues.ValueHolder valueHolder =
                resolvedValues.getArgumentValue(paramIndex, paramType, paramName, usedValueHolders);
        // 如果没有获取到value并且不支持自动注入的方式,尝试通过无类型参数值匹配获取value,这里可以匹配类型转换后的参数,例如"1" -> 1,String -> int
        if (valueHolder == null && (!autowiring || paramTypes.length == resolvedValues.getArgumentCount())) {
            valueHolder = resolvedValues.getGenericArgumentValue(null, null, usedValueHolders);
        }
        if (valueHolder != null) {
            usedValueHolders.add(valueHolder);
            Object originalValue = valueHolder.getValue();
            Object convertedValue;
            if (valueHolder.isConverted()) {
                convertedValue = valueHolder.getConvertedValue();
                args.preparedArguments[paramIndex] = convertedValue;
            }
            else { // 如果没有转换过,则要需要判断是否需要通过类型装换器装换类型
                ConstructorArgumentValues.ValueHolder sourceHolder =
                        (ConstructorArgumentValues.ValueHolder) valueHolder.getSource();
                Object sourceValue = sourceHolder.getValue();
                MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, paramIndex);
                try {
                    convertedValue = converter.convertIfNecessary(originalValue, paramType, methodParam);
                    args.resolveNecessary = true;
                    args.preparedArguments[paramIndex] = sourceValue;
                }
                catch (TypeMismatchException ex) {
                    throw new UnsatisfiedDependencyException(
                            mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam),
                            "Could not convert argument value of type [" +
                            ObjectUtils.nullSafeClassName(valueHolder.getValue()) +
                            "] to required type [" + paramType.getName() + "]: " + ex.getMessage());
                }
            }
            args.arguments[paramIndex] = convertedValue;
            args.rawArguments[paramIndex] = originalValue;
        }
        else {
            MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, paramIndex);
            // 到这里如果不支持自动装配,就没有别的办法了,抛出异常
            if (!autowiring) {
                throw new UnsatisfiedDependencyException(
                        mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam),
                        "Ambiguous argument values for parameter of type [" + paramType.getName() +
                        "] - did you specify the correct bean references as arguments?");
            }
            try {
                // 参数自动装配的处理
                Object autowiredArgument =
                        resolveAutowiredArgument(methodParam, beanName, autowiredBeanNames, converter);
                args.rawArguments[paramIndex] = autowiredArgument;
                args.arguments[paramIndex] = autowiredArgument;
                args.preparedArguments[paramIndex] = new AutowiredArgumentMarker();
                args.resolveNecessary = true;
            }
            catch (BeansException ex) {
                throw new UnsatisfiedDependencyException(
                        mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), ex);
            }
        }
    }
    for (String autowiredBeanName : autowiredBeanNames) {
        // 注册自动装配的bean的依赖关系
        this.beanFactory.registerDependentBean(autowiredBeanName, beanName);
        if (this.beanFactory.logger.isDebugEnabled()) {
            this.beanFactory.logger.debug("Autowiring by type from bean name '" + beanName +
                    "' via " + (methodOrCtor instanceof Constructor ? "constructor" : "factory method") +
                    " to bean named '" + autowiredBeanName + "'");
        }
    }
    return args;
}

SimpleInstantiationStrategy:

public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner,
        final Constructor<?> ctor, Object... args) {
    // 如果没有配置lookup-method或replace-method直接使用反射创建对象,否则需要使用CGLIB进行动态代理根据配置动态替换方法
    if (bd.getMethodOverrides().isEmpty()) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    ReflectionUtils.makeAccessible(ctor);
                    return null;
                }
            });
        }
        // 反射使用选中的构造方法进行初始化
        return BeanUtils.instantiateClass(ctor, args);
    }
    else {
        /* CGLIB动态代理 */
        return instantiateWithMethodInjection(bd, beanName, owner, ctor, args);
    }
}

CglibSubclassingInstantiationStrategy:

protected Object instantiateWithMethodInjection(RootBeanDefinition bd, String beanName, BeanFactory owner,
        Constructor<?> ctor, Object... args) {
    /* CGLIB动态代理 */
    return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
}

CglibSubclassingInstantiationStrategy.CglibSubclassCreator:

public Object instantiate(Constructor<?> ctor, Object... args) {
    Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
    Object instance;
    if (ctor == null) {
        instance = BeanUtils.instantiateClass(subclass);
    }
    else {
        try {
            Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
            instance = enhancedSubclassConstructor.newInstance(args);
        }
        catch (Exception ex) {
            throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
                    "Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
        }
    }
    Factory factory = (Factory) instance;
    factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
            new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner), // lookup-method处理
            new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)}); // replace-method处理
    return instance;
}

这里需要读者对CGLIB创建代理类的方式有一定的了解,我们也会在后续Spring AOP的文章中进行详细介绍。根据参数匹配构造方法进行实例化bean的过程到这里就结束了,如果没有参数,会使用无参构造方法进行实例化,过程相似,就不多赘述了,我们继续来看后续的步骤:
DefaultSingletonBeanRegistry:

protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
    Assert.notNull(singletonFactory, "Singleton factory must not be null");
    synchronized (this.singletonObjects) {
        if (!this.singletonObjects.containsKey(beanName)) {
            this.singletonFactories.put(beanName, singletonFactory);
            this.earlySingletonObjects.remove(beanName);
            this.registeredSingletons.add(beanName);
        }
    }
}

上文中我们提倒了多次循环依赖,解决办法就是在这里了,通过提前暴露ObjectFactory放入缓存中,这样其他bean依赖当前bean时,从缓存中得到的只是刚刚初始化完但还没有填充任何属性的bean的引用,当前bean创建完成之后依赖它的bean自然能够通过引用获取到当前bean,这样就解决了循环依赖。下面我们就来分析属性填充的过程:
AbstractAutowireCapableBeanFactory:

protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
    PropertyValues pvs = mbd.getPropertyValues();
    if (bw == null) {
        if (!pvs.isEmpty()) {
            // 如果属性不为空但实例空,无处填充,抛出异常
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
        }
        else {
            return; // 空实例无需处理
        }
    }
    // 填充属性之前给InstantiationAwareBeanPostProcessors一个机会改变bean的状态,如可以用来支持属性注入的类型
    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; // 如果返回不需要继续填充属性直接返回
    }
    if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
            mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
        MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
        if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
            /* 根据name自动装配 */
            autowireByName(beanName, mbd, bw, newPvs);
        }
        if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
            /* 根据type自动装配 */
            autowireByType(beanName, mbd, bw, newPvs);
        }
        pvs = newPvs;
    }
    // 是否有后处理器
    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    // 是否需要依赖检查
    boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
    if (hasInstAwareBpps || needsDepCheck) {
        PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        if (hasInstAwareBpps) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    /* 应用InstantiationAwareBeanPostProcessor进行属性后处理 */
                    pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    if (pvs == null) {
                        return;
                    }
                }
            }
        }
        if (needsDepCheck) {
            // 属性依赖检查
            checkDependencies(beanName, mbd, filteredPds, pvs);
        }
    }
    /* 应用属性到bean */
    applyPropertyValues(beanName, mbd, bw, pvs);
}

AbstractAutowireCapableBeanFactory:

protected void autowireByName(
        String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    // 找到需要依赖注入的属性,不包括基本类型和String等这种简单的类型
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        if (containsBean(propertyName)) {
            // 递归初始化bean
            Object bean = getBean(propertyName);
            pvs.add(propertyName, bean);
            // 注册依赖
            registerDependentBean(propertyName, beanName);
            if (logger.isDebugEnabled()) {
                logger.debug("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");
            }
        }
    }
}

AbstractAutowireCapableBeanFactory:

protected void autowireByType(
        String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    // 如果有自定义属性装换器,则应用
    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }
    Set<String> autowiredBeanNames = new LinkedHashSet<String>(4);
    // 找到需要依赖注入的属性,不包括基本类型和String等这种简单的类型
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        try {
            PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
            // 按类型注入属性时Object类型的属性是没有意义的
            if (Object.class != pd.getPropertyType()) {
                // 获取set方法的参数
                MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
                boolean eager = !PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass());
                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.isDebugEnabled()) {
                        logger.debug("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);
        }
    }
}

DefaultListableBeanFactory:

public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName,
        Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
    descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
    // 前几个分支的判断是对几个特殊类型的处理,java8的Optional、javax.inject.Provider和ObjectFactory
    if (javaUtilOptionalClass == descriptor.getDependencyType()) {
        return new OptionalDependencyFactory().createOptionalDependency(descriptor, requestingBeanName);
    }
    else if (ObjectFactory.class == descriptor.getDependencyType() ||
            ObjectProvider.class == descriptor.getDependencyType()) {
        return new DependencyObjectProvider(descriptor, requestingBeanName);
    }
    else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
        return new Jsr330ProviderFactory().createDependencyProvider(descriptor, requestingBeanName);
    }
    else {
        Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
                descriptor, requestingBeanName);
        if (result == null) {
            /* 处理依赖 */
            result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
        }
        return result;
    }
}

DefaultListableBeanFactory:

public Object doResolveDependency(DependencyDescriptor descriptor, String beanName,
        Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
    InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
    try {
        Object shortcut = descriptor.resolveShortcut(this);
        if (shortcut != null) {
            return shortcut;
        }
        Class<?> type = descriptor.getDependencyType();
        Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
        if (value != null) {
            if (value instanceof String) {
                String strVal = resolveEmbeddedValue((String) value);
                BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null);
                // EL表达式的处理
                value = evaluateBeanDefinitionString(strVal, bd);
            }
            // 类型装换器做类型转换处理
            TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
            return (descriptor.getField() != null ?
                    converter.convertIfNecessary(value, type, descriptor.getField()) :
                    converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
        }
        // Array数组、Collection集合、Map三种复杂类型的处理
        Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
        if (multipleBeans != null) {
            return multipleBeans;
        }
        // 根据类型候选的bean
        Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
        if (matchingBeans.isEmpty()) {
            if (descriptor.isRequired()) {
                // 如果根据type没有获取到候选的bean并且设置了required,抛出异常
                raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
            }
            return null;
        }
        String autowiredBeanName;
        Object instanceCandidate;
        if (matchingBeans.size() > 1) {
            // 按照@Primary(在注解扫描的文章中提到过这个注解) --> order(PriorityOrdered、Ordered、@Order) --> beanName匹配,优先级降序匹配
            autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
            if (autowiredBeanName == null) {
                if (descriptor.isRequired() || !indicatesMultipleBeans(type)) {
                    return descriptor.resolveNotUnique(type, matchingBeans);
                }
                else {
                    return null;
                }
            }
            instanceCandidate = matchingBeans.get(autowiredBeanName);
        }
        else {
            // 这里已经确定只有一个匹配项
            Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
            autowiredBeanName = entry.getKey();
            instanceCandidate = entry.getValue();
        }
        if (autowiredBeanNames != null) {
            autowiredBeanNames.add(autowiredBeanName);
        }
        return (instanceCandidate instanceof Class ?
                descriptor.resolveCandidate(autowiredBeanName, type, this) : instanceCandidate);
    }
    finally {
        ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
    }
}

下面是InstantiationAwareBeanPostProcessor的postProcessPropertyValues的应用,@Autowire、@Value、@Resource、@Required等注解都是都是在这里发挥作用的,我们以@Autowire注解作为示例,锁定AutowiredAnnotationBeanPostProcessor:

public PropertyValues postProcessPropertyValues(
        PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {
    /* 获取注解元数据 */
    InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
    try {
        /* 注入 */
        metadata.inject(bean, beanName, pvs);
    }
    catch (BeanCreationException ex) {
        throw ex;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
    }
    return pvs;
}

AutowiredAnnotationBeanPostProcessor:

private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, PropertyValues pvs) {
    String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
    InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); // 尝试从缓存中获取
    if (InjectionMetadata.needsRefresh(metadata, clazz)) {
        synchronized (this.injectionMetadataCache) {
            metadata = this.injectionMetadataCache.get(cacheKey);
            if (InjectionMetadata.needsRefresh(metadata, clazz)) {
                if (metadata != null) {
                    metadata.clear(pvs);
                }
                try {
                    /* 构建自动装配元数据 */
                    metadata = buildAutowiringMetadata(clazz);
                    this.injectionMetadataCache.put(cacheKey, metadata);
                }
                catch (NoClassDefFoundError err) {
                    throw new IllegalStateException("Failed to introspect bean class [" + clazz.getName() +
                            "] for autowiring metadata: could not find class that it depends on", err);
                }
            }
        }
    }
    return metadata;
}

AutowiredAnnotationBeanPostProcessor:

private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
    Class<?> targetClass = clazz;
    do {
        final LinkedList<InjectionMetadata.InjectedElement> currElements =
                new LinkedList<InjectionMetadata.InjectedElement>();
        ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() {
            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                // 获取属性上的注解的配置属性,包括@Autowire和@Value注解
                AnnotationAttributes ann = findAutowiredAnnotation(field);
                if (ann != null) {
                    // 不支持在static属性上使用@Autowire注解
                    if (Modifier.isStatic(field.getModifiers())) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Autowired annotation is not supported on static fields: " + field);
                        }
                        return;
                    }
                    // 获取required属性
                    boolean required = determineRequiredStatus(ann);
                    currElements.add(new AutowiredFieldElement(field, required));
                }
            }
        });
        ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {
            @Override
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
                if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                    return;
                }
                // 获取方法上的注解的配置属性,包括@Autowire和@Value注解
                AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
                if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                    // 不支持在static方法上使用@Autowire注解
                    if (Modifier.isStatic(method.getModifiers())) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Autowired annotation is not supported on static methods: " + method);
                        }
                        return;
                    }
                    // 方法必须有参数,不然没意义
                    if (method.getParameterTypes().length == 0) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Autowired annotation should only be used on methods with parameters: " +
                                    method);
                        }
                    }
                    // 获取required属性
                    boolean required = determineRequiredStatus(ann);
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new AutowiredMethodElement(method, required, pd));
                }
            }
        });
        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    }
    while (targetClass != null && targetClass != Object.class);
    return new InjectionMetadata(clazz, elements);
}

InjectionMetadata:

public void inject(Object target, String beanName, PropertyValues pvs) throws Throwable {
    Collection<InjectedElement> elementsToIterate =
            (this.checkedElements != null ? this.checkedElements : this.injectedElements);
    if (!elementsToIterate.isEmpty()) {
        boolean debug = logger.isDebugEnabled();
        for (InjectedElement element : elementsToIterate) {
            if (debug) {
                logger.debug("Processing injected element of bean '" + beanName + "': " + element);
            }
            /* 注入 */
            element.inject(target, beanName, pvs);
        }
    }
}

这里的注入有field属性的注入和method方法的注入,我们以属性的注入为例,method方法的注入也就是调用set方法为属性赋值,原理相似。
AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement:

protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
    Field field = (Field) this.member;
    Object value;
    if (this.cached) {
        // 如果已经缓存,判断是否需要处理依赖,需要则处理,不需要直接返回,处理依赖的流程上文分析过
        value = resolvedCachedArgument(beanName, this.cachedFieldValue);
    }
    else {
        DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
        desc.setContainingClass(bean.getClass());
        Set<String> autowiredBeanNames = new LinkedHashSet<String>(1);
        TypeConverter typeConverter = beanFactory.getTypeConverter();
        try {
            // 处理依赖,流程上文分析过
            value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
        }
        catch (BeansException ex) {
            throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
        }
        synchronized (this) {
            if (!this.cached) {
                if (value != null || this.required) {
                    this.cachedFieldValue = desc;
                    registerDependentBeans(beanName, autowiredBeanNames); // 注册依赖
                    if (autowiredBeanNames.size() == 1) {
                        String autowiredBeanName = autowiredBeanNames.iterator().next();
                        if (beanFactory.containsBean(autowiredBeanName)) {
                            // 按照类型进行匹配
                            if (beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
                                // 缓存匹配到的属性的值
                                this.cachedFieldValue = new ShortcutDependencyDescriptor(
                                        desc, autowiredBeanName, field.getType());
                            }
                        }
                    }
                }
                else {
                    this.cachedFieldValue = null;
                }
                this.cached = true;
            }
        }
    }
    if (value != null) {
        ReflectionUtils.makeAccessible(field);
        field.set(bean, value); // 反射为属性赋值
    }
}

属性的提取已经完成,下面就是属性的应用了:
AbstractAutowireCapableBeanFactory:

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    if (pvs == null || pvs.isEmpty()) {
        return;
    }
    MutablePropertyValues mpvs = null;
    List<PropertyValue> original;
    if (System.getSecurityManager() != null) {
        if (bw instanceof BeanWrapperImpl) {
            ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
        }
    }
    if (pvs instanceof MutablePropertyValues) {
        mpvs = (MutablePropertyValues) pvs;
        if (mpvs.isConverted()) {
            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;
    }
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
    List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
    boolean resolveNecessary = false;
    // 遍历,将属性转换成类的对应属性的类型
    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);
            }
            // 为了避免重复转换已经创建的bean实例,保存转换过的值
            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 {
        // 调用对应属性的setter方法为属性赋值
        bw.setPropertyValues(new MutablePropertyValues(deepCopy));
    }
    catch (BeansException ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Error setting property values", ex);
    }
}

bean属性填充完毕后,接下来就是调用各种初始化方法:
AbstractAutowireCapableBeanFactory:

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                /* 调用Aware的相关set方法 */
                invokeAwareMethods(beanName, bean);
                return null;
            }
        }, getAccessControlContext());
    }
    else {
        /* 调用Aware的相关set方法 */
        invokeAwareMethods(beanName, bean);
    }
    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        // 在bean属性填充之后,初始化方法调用之前,回调BeanPostProcessor的postProcessBeforeInitialization方法。在标签解析的文章中我们看到Spring注册了ApplicationContextAwareProcessor,就是在这里应用的,是对另外一些Aware方法的调用
        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()) {
        // 在初始化方法调用之后,回调BeanPostProcessor的postProcessAfterInitialization方法,之前分析过,不再赘述
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }
    return wrappedBean;
}

AbstractAutowireCapableBeanFactory:

private void invokeAwareMethods(final String beanName, final Object bean) {
    if (bean instanceof Aware) {
        if (bean instanceof BeanNameAware) {
            ((BeanNameAware) bean).setBeanName(beanName);
        }
        if (bean instanceof BeanClassLoaderAware) {
            ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
        }
        if (bean instanceof BeanFactoryAware) {
            ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
        }
    }
}

很简单,就是对几个Aware的相关set方法的调用。
AbstractAutowireCapableBeanFactory:

protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
        throws Throwable {
    boolean isInitializingBean = (bean instanceof InitializingBean);
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }
        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                    @Override
                    public Object run() throws Exception {
                        // 调用InitializingBean的afterPropertiesSet方法
                        ((InitializingBean) bean).afterPropertiesSet();
                        return null;
                    }
                }, getAccessControlContext());
            }
            catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        }
        else {
            // 调用InitializingBean的afterPropertiesSet方法
            ((InitializingBean) bean).afterPropertiesSet();
        }
    }
    if (mbd != null) {
        String initMethodName = mbd.getInitMethodName();
        if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                !mbd.isExternallyManagedInitMethod(initMethodName)) {
            /* 调用自定义初始化方法 */
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}

AbstractAutowireCapableBeanFactory:

protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
        throws Throwable {
    String initMethodName = mbd.getInitMethodName();
    // 找到自定义的init方法
    final Method initMethod = (mbd.isNonPublicAccessAllowed() ?
            BeanUtils.findMethod(bean.getClass(), initMethodName) :
            ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));
    if (initMethod == null) {
        if (mbd.isEnforceInitMethod()) {
            throw new BeanDefinitionValidationException("Couldn't find an init method named '" +
                    initMethodName + "' on bean with name '" + beanName + "'");
        }
        else {
            if (logger.isDebugEnabled()) {
                logger.debug("No default init method named '" + initMethodName +
                        "' found on bean with name '" + beanName + "'");
            }
            return;
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Invoking init method  '" + initMethodName + "' on bean with name '" + beanName + "'");
    }
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                ReflectionUtils.makeAccessible(initMethod);
                return null;
            }
        });
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws Exception {
                    initMethod.invoke(bean); // 调用init方法
                    return null;
                }
            }, getAccessControlContext());
        }
        catch (PrivilegedActionException pae) {
            InvocationTargetException ex = (InvocationTargetException) pae.getException();
            throw ex.getTargetException();
        }
    }
    else {
        try {
            ReflectionUtils.makeAccessible(initMethod);
            initMethod.invoke(bean); // 调用init方法
        }
        catch (InvocationTargetException ex) {
            throw ex.getTargetException();
        }
    }
}

接下来是Spring提供的销毁方法的注册:
AbstractBeanFactory:

protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
    AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
    // 非原型并且含有销毁方法(bean实现了DisposableBean或者自定义了destory-method或者实现了jdk的Closable|AutoClosable)或者有可用的DestructionAwareBeanPostProcessor
    if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
        if (mbd.isSingleton()) {
            // 单例直接放入disposableBeans缓存中,bean销毁时会取出并调用相关方法
            registerDisposableBean(beanName,
                    new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
        }
        else {
            Scope scope = this.scopes.get(mbd.getScope());
            if (scope == null) {
                throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
            }
            // 自定义的scope调用其registerDestructionCallback方法
            scope.registerDestructionCallback(beanName,
                    new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
        }
    }
}

到这里整个bean的创建就完成了。

  • 5
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值