Spring 中的 Bean 加载过程?

之前写过 bean 的解析,这篇来讲讲 bean 的加载,加载要比 bean 的解析复杂些,该文之前在小编原文中有发表过,要看原文的可以直接点击原文查看,从之前的例子开始,Spring 中加载一个 bean 的方式:

TestBean bean = factory.getBean(“testBean”);

来看看 getBean(String name)方法源码,

@Override public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false);
}

该 getBean(String name)方法位于 AbstractBeanFactory 抽象类中,AbstractBeanFactory 与 XmlBeanFactory 类关系可以看下图:

接下去跟进 doGetBean()方法源码:

[![](http://bbs.itmayiedu.com/upload/9ed8152e18e24f7d90028dc7f7682f70.gif)](javascript:void(0); "复制代码")

protected  T doGetBean( final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { // 提取beanName
    final String beanName = transformedBeanName(name);
    Object 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 + "'");
            }
        } // 返回实例,有时存在如BeanFactory这样情况时并不是直接返回实例本身而是返回指定方法返回的实例
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    } else { // Fail if we're already creating this bean instance: // We're assumably within a circular reference.
        if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName);
        } // Check if bean definition exists in this factory.
        BeanFactory parentBeanFactory = getParentBeanFactory(); // 如果在所有已经加载的类中没有beanName则会尝试从parentBeanFactory中检测
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent.
            String nameToLookup = originalBeanName(name); // 到BeanFactory查找
            if (args != null) { // Delegation to parent with explicit args.
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            } else { // No args -> delegate to standard getBean method.
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
        } // 如果不是只做类型检查则是创建bean
        if (!typeCheckOnly) {
            markBeanAsCreated(beanName);
        } try { // 将存储XML配置文件的GernericBeanDefinition转换成RootBeanDefinition,如果BeanName是子Bean的话会合并父类的相关属性
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on.
            String[] dependsOn = mbd.getDependsOn(); // 如果存在依赖的话要递归实例化依赖的bean
            if (dependsOn != null) { for (String dependsOnBean : dependsOn) { if (isDependent(beanName, dependsOnBean)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
                    }
                    registerDependentBean(dependsOnBean, beanName);
                    getBean(dependsOnBean);
                }
            } // Create bean instance. // 依赖的bean实例化完后就可以实例化mbd了
            if (mbd.isSingleton()) {
                sharedInstance = getSingleton(beanName, new ObjectFactory() {
                    @Override public Object getObject() throws BeansException { try { return createBean(beanName, mbd, args);
                        } catch (BeansException ex) { // Explicitly remove instance from singleton cache: It might have been put there // eagerly by the creation process, to allow for circular reference resolution. // Also remove any beans that received a temporary reference to the bean.
 destroySingleton(beanName); throw ex;
                        }
                    }
                });
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            } else if (mbd.isPrototype()) { // It's a prototype -> create a new instance.
                Object prototypeInstance = null; try {
                    beforePrototypeCreation(beanName);
                    prototypeInstance = createBean(beanName, mbd, args);
                } finally {
                    afterPrototypeCreation(beanName);
                }
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            } else { // 在对应的scope上实例化bean
                String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'");
                } try {
                    Object scopedInstance = scope.get(beanName, new ObjectFactory() {
                        @Override public Object getObject() throws BeansException {
                            beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args);
                            } finally {
                                afterPrototypeCreation(beanName);
                            }
                        }
                    });
                    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;
        }
    } // 检查需要的类型是否符合实例bean的实际类型
    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;
}

[](javascript:void(0); “复制代码”)

整个 bean 加载的过程步骤相对繁琐,主要步骤有以下几点:

  1. 转换 beanName
    要知道平时开发中传入的参数 name 可能只是别名,也可能是 FactoryBean,所以需要进行解析转换,一般会进行以下解析:
    (1)消除修饰符,比如 name=“&test”,会去除&使 name=“test”;
    (2)取 alias 表示的最后的 beanName,比如别名 test01 指向名称为 test02 的 bean 则返回 test02。

  2. 从缓存中加载实例
    实例在 Spring 的同一个容器中只会被创建一次,后面再想获取该 bean 时,就会尝试从缓存中获取;如果获取不到的话再从 singletonFactories 中加载。

  3. 实例化 bean
    缓存中记录的 bean 一般只是最原始的 bean 状态,这时就需要对 bean 进行实例化。如果得到的是 bean 的原始状态,但又要对 bean 进行处理,这时真正需要的是工厂 bean 中定义的 factory-method 方法中返回的 bean,上面源码中的 getObjectForBeanInstance 就是来完成这个工作的。

  4. 检测 parentBeanFacotory
    从源码可以看出如果缓存中没有数据会转到父类工厂去加载,源码中的!containsBeanDefinition(beanName)就是检测如果当前加载的 xml 配置文件中不包含 beanName 所对应的配置,就只能到 parentBeanFacotory 去尝试加载 bean。

  5. 存储 XML 配置文件的 GernericBeanDefinition 转换成 RootBeanDefinition 之前的文章介绍过 XML 配置文件中读取到的 bean 信息是存储在 GernericBeanDefinition 中的,但 Bean 的后续处理是针对于 RootBeanDefinition 的,所以需要转换后才能进行后续操作。

  6. 初始化依赖的 bean
    这里应该比较好理解,就是 bean 中可能依赖了其他 bean 属性,在初始化 bean 之前会先初始化这个 bean 所依赖的 bean 属性。

  7. 创建 bean
    Spring 容器根据不同 scope 创建 bean 实例。
    整个流程就是如此,下面会讲解一些重要步骤的源码。

上面有提到,单例在 Spring 中的同一容器中只会被创建一次,后面再获取 bean 的话会直接从缓存中获取,这里是尝试加载,先从缓存中加载,再次就是从 singletonFactories 中加载;因为在 bean 中可能会在依赖注入,要避免循环依赖,Spring 创建 bean 时会不等 bean 创建完成就会将创建该 bean 的 ObjectFactory 提前曝光加入到缓存中,但下一个 bean 创建时要依赖上个 bean 的话,就直接使用 ObjectFacotry。

@Override public Object getSingleton(String beanName) { return getSingleton(beanName, true);  // true表示允许早期依赖
} protected Object getSingleton(String beanName, boolean allowEarlyReference) { // 尝试从缓存获取实例
    Object singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { synchronized (this.singletonObjects) { // 若该bean正在加载则不处理
            singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null && allowEarlyReference) {
                ObjectFactory singletonFactory = this.singletonFactories.get(beanName); if (singletonFactory != null) {
                    singletonObject = singletonFactory.getObject(); // 存入到缓存中
                    this.earlySingletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName);
                }
            }
        }
    } return (singletonObject != NULL_OBJECT ? singletonObject : null);
} /* 这两个方法在DefaultSingletonBeanRegistry类中 */

源码可以看出这个方法先尝试从 singletonObjects 中获取实例,如果获取不到值就从 earlySingletonObject 中去获取,如果再获取不到的话则到 singletonFactories 里获取 beanName 对应的 ObjectFactory,再调用这个 ObjectFactory 的 getObject 来创建 bean,并放到 earlySingletonObject 中,并且从 singletonFactories 里 remove 掉这个 ObjectFactory。这里有几个存储 bean 的不同 map:
-singletonObjects:保存 BeanName 和创建 bean 实例之间的关系。
-singletonFactories:保存 BeanName 和创建 bean 实例的工厂之间的关系。
-earlySingletonObject:保存 BeanName 和创建 bean 实例之间的关系,与-singletonObjects 不同的是当一个单例 bean 被放到里面后,那当 bean 在创建过程中,就可以通过 getBean 方法获取到,可以用来检测循环引用。
-registeredSingletons:保存当前所有已注册的 bean。

如果上面缓存中不存在已经加载的单例 bean 就要重新开始 bean 的加载过程了,Spring 中使用 getSingleton 重载方法实现 bean 的加载过程。


public Object getSingleton(String beanName, ObjectFactory singletonFactory) { Assert.notNull(beanName, "'beanName' must not be null"); synchronized (this.singletonObjects) { // 先检查bean是否已经加载 Object singletonObject = this.singletonObjects.get(beanName); // 如果空才进行singleton的bean的初始化 if (singletonObject == null) { if (this.singletonsCurrentlyInDestruction) { throw new BeanCreationNotAllowedException(beanName, "Singleton bean creation not allowed while the 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 + "'"); } beforeSingletonCreation(beanName); boolean newSingleton = false; boolean recordSuppressedExceptions = (this.suppressedExceptions == null); if (recordSuppressedExceptions) { this.suppressedExceptions = new LinkedHashSet(); } try { // 初始化bean singletonObject = singletonFactory.getObject(); newSingleton = true; } catch (IllegalStateException ex) { // Has the singleton object implicitly appeared in the meantime -> // if yes, proceed with it since the exception indicates that state. 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; } afterSingletonCreation(beanName); } if (newSingleton) { // 存入缓存 addSingleton(beanName, singletonObject); } } return (singletonObject != NULL_OBJECT ? singletonObject : null); } }

这段代码使用了回调方法,使程序可以在单例创建的前后做一些准备及处理操作,真正的获取单例 bean 的方法其实并不是在这个方法实现的,而是在 ObjectFactory 类型的实例 singletonFactory 中实现的。

下面准备创建 bean

看看 createBean()方法源码(该方法在 AbstractAutowireCapableBeanFactory 类中):


protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException { if (logger.isDebugEnabled()) { logger.debug("Creating instance of bean '" + beanName + "'"); } // 锁定class,根据设置的class属性或根据className来解析Class resolveBeanClass(mbd, beanName); // 验证和准备覆盖的方法 try { mbd.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { // 用BeanPostProcessors返回代理来替代真正的实例 Object bean = resolveBeforeInstantiation(beanName, mbd); if (bean != null) { return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } Object beanInstance = doCreateBean(beanName, mbd, args); if (logger.isDebugEnabled()) { logger.debug("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; }

从 createBean()方法源码可以看出主要做了以下操作:
1. 根据设置的 class 属性或根据 className 来解析 Class;
2. 对覆盖进行标记并验证,在 Spring 配置中是存在 lookup-mothod 和 replace-method 的,这两个配置的加载其实就是将配置统一存放在 BeanDefinition 中的 methodOverrides 属性里,这个方法的操作也就是针对于这两个配置的;
3. 应用初始化前的后处理器,最后创建 bean。
在 createBean()方法里执行完 resolveBeforeInstantiation 方法后,如果创建了代理且不为空的话就直接返回,否则需要进行常规 bean 的创建,这个创建过程是在 doCreateBean 中完成的,跟进源码:


protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) { // Instantiate the bean. 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); // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); mbd.postProcessed = true; } } // 检测循环依赖,是否需要提早曝光 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初始化完成前将创建实例的ObjectFactory加入工厂 addSingletonFactory(beanName, new ObjectFactory() { @Override public Object getObject() throws BeansException { // 对bean再次依赖引用 // AOP也是在这里将advice动态织入bean中,若没有则直接返回bean,不做处理 return getEarlyBeanReference(beanName, mbd, bean); } }); } // Initialize the bean instance. Object exposedObject = bean; try { // 填充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) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set 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 { // 依据scopse注册bean registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }

上面源码完成的操作可以概括为以下几点:
1. 开始是单例的话要先清除缓存;
2. 实例化 bean,将 BeanDefinition 转换为 BeanWrapper;
3. 使用 MergedBeanDefinitionPostProcessor,Autowired 注解就是通过此方法实现类型的预解析;
4. 解决循环依赖问题;
5. 填充属性,将属性填充到 bean 实例中;
6. 注册 DisposableBean;
7. 创建完成并返回

接下来创建 bean 实例,看 createBeanInstance()方法:


protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) { // 解析class 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()); } // 若工厂方法不为空则使用工厂方法初始化 if (mbd.getFactoryMethodName() != null) { return instantiateUsingFactoryMethod(beanName, mbd, args); } // Shortcut when re-creating the same bean... 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); } // No special handling: simply use no-arg constructor. return instantiateBean(beanName, mbd); }

可以看出如果在 RootBeanDefinition 中存在 factoryMethodName 属性,或者说配置文件中配置了 factory-method,那么 Spring 会尝试使用 instantiateUsingFactoryMethod(beanName, mbd, args)方法根据 RootBeanDefinition 中的配置生成 bean 实例。
再解析构造方法并进行实例化,Spring 会根据参数及类型判断使用哪个构造方法再进行实例化。判断调用哪个构造方法的过程会采用缓存机制,如果已经解析过则不需要重复解析而是从 RootBeanDefinition 中的属性 resolvedConstructorOrFactoryMethod 缓存的值去取,不然则需要再次解析。

创建 bean 后接下来就进行属性注入,属性注入的操作在 populateBean()方法中,跟进源码:


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 { // 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. 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.AUTOWIREBYNAME || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIREBYTYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIREBYNAME) { autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIREBYTYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCYCHECKNONE); if (hasInstAwareBpps || needsDepCheck) { PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); if (hasInstAwareBpps) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvs == null) { return; } } } } if (needsDepCheck) { checkDependencies(beanName, mbd, filteredPds, pvs); } } applyPropertyValues(beanName, mbd, bw, pvs); }

在 populateBean 方法的中的主要处理流程:
1. InstantiationAwareBeanPostProcessor 处理器的 postProcessAfterInstantiation 方法控制程序是否继续填充属性;
2. 根据注入类型提取依赖的 bean,并存入 PropertyValues 中;
3. 应用 InstantiationAwareBeanPostProcessor 处理器的 postProcessPropertyValues 方法对属性在填充前再次处理,主要还是验证属性;
4. 将所有 PropertyValues 中的属性填充到 BeanWrapper 中。

最后初始化 bean

学过 Spring 的都知道 bean 配置时有一个 init-method 属性,这个属性的作用是在 bean 实例化前调用 init-method 指定的方法进行需要的实例化操作,现在就进入这个方法了;Spring 中程序已经执行过 bean 的实例化,并且进行了属性的填充,而就在这时将会调用用户设定的初始化方法。


protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction() { @Override public Object run() { invokeAwareMethods(beanName, bean); return null; } }, getAccessControlContext()); } else { // 特殊bean处理 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; }

最后加载完 Bean 并执行完初始化操作后,一个 bean 的加载基本就结束了。