publicvoidrefresh()throws BeansException, IllegalStateException {synchronized(this.startupShutdownMonitor){// Prepare this context for refreshing.prepareRefresh();// Tell the subclass to refresh the internal bean factory.// spring 解析 xml 配置文件将要创建的所有 bean 的配置信息保存起来
ConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory();// Prepare the bean factory for use in this context.prepareBeanFactory(beanFactory);try{// Allows post-processing of the bean factory in context subclasses.postProcessBeanFactory(beanFactory);// Invoke factory processors registered as beans in the context.invokeBeanFactoryPostProcessors(beanFactory);// Register bean processors that intercept bean creation.registerBeanPostProcessors(beanFactory);// Initialize message source for this context.// 支持国际化功能的initMessageSource();// Initialize event multicaster for this context.initApplicationEventMulticaster();// Initialize other special beans in specific context subclasses.// 空方法,留给子类实现的onRefresh();// Check for listener beans and register them.registerListeners();// Instantiate all remaining (non-lazy-init) singletons.// 初始化所有单实例的 beanfinishBeanFactoryInitialization(beanFactory);// Last step: publish corresponding event.finishRefresh();}catch(BeansException ex){// Destroy already created singletons to avoid dangling resources.destroyBeans();// Reset 'active' flag.cancelRefresh(ex);// Propagate exception to caller.throw ex;}}}
3.1、beanFactory 保存所有 bean 的配置信息
// spring 解析 xml 配置文件将要创建的所有 bean 的配置信息保存起来
ConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory();
3.2、finishBeanFactoryInitialization(beanFactory);
protectedvoidfinishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory){// Initialize conversion service for this context.if(beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME)&&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)){
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));}// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class,false,false);for(String weaverAwareName : weaverAwareNames){getBean(weaverAwareName);}// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);// Allow for caching all bean definition metadata, not expecting further changes.
beanFactory.freezeConfiguration();// Instantiate all remaining (non-lazy-init) singletons.// 初始化所有单实例的 bean
beanFactory.preInstantiateSingletons();}
4、初始化所有单实例 bean
publicvoidpreInstantiateSingletons()throws BeansException {if(this.logger.isDebugEnabled()){this.logger.debug("Pre-instantiating singletons in "+this);}
List<String> beanNames;synchronized(this.beanDefinitionMap){// Iterate over a copy to allow for init methods which in turn register new bean definitions.// While this may not be part of the regular factory bootstrap, it does otherwise work fine.// 获取所有要创建的 bean 的 id// beanNames: {"person01", "person02"}
beanNames =newArrayList<String>(this.beanDefinitionNames);}// 遍历 beanNames,创建 beanfor(String beanName : beanNames){// 根据 bean id 获取到 bean 的定义信息
RootBeanDefinition bd =getMergedLocalBeanDefinition(beanName);// 创建非抽象、单实例、非懒加载的 beanif(!bd.isAbstract()&& bd.isSingleton()&&!bd.isLazyInit()){// 是否是实现 FactoryBean 接口的 beanif(isFactoryBean(beanName)){final FactoryBean<?> factory =(FactoryBean<?>)getBean(FACTORY_BEAN_PREFIX + beanName);boolean isEagerInit;if(System.getSecurityManager()!= null && factory instanceofSmartFactoryBean){
isEagerInit = AccessController.doPrivileged(newPrivilegedAction<Boolean>(){@Overridepublic Boolean run(){return((SmartFactoryBean<?>) factory).isEagerInit();}},getAccessControlContext());}else{
isEagerInit =(factory instanceofSmartFactoryBean&&((SmartFactoryBean<?>) factory).isEagerInit());}if(isEagerInit){getBean(beanName);}}else{// 创建 beangetBean(beanName);}}}}
5、创建 bean
public Object getBean(String name)throws BeansException {returndoGetBean(name, null, null,false);}
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;// Eagerly check singleton cache for manually registered singletons.// 从已经创建的所有单实例 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 =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)){thrownewBeanCurrentlyInCreationException(beanName);}// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory =getParentBeanFactory();if(parentBeanFactory != null &&!containsBeanDefinition(beanName)){// Not found -> check parent.
String nameToLookup =originalBeanName(name);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);}}// 防止多线程创建多次if(!typeCheckOnly){// 标记这个 bean 已经创建了markBeanAsCreated(beanName);}try{final RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);checkMergedBeanDefinition(mbd, beanName, args);// Guarantee initialization of beans that the current bean depends on.// 获取当前 bean 依赖的 bean,就是 depends-on 属性,如果有就创建
String[] dependsOn = mbd.getDependsOn();if(dependsOn != null){for(String dependsOnBean : dependsOn){if(isDependent(beanName, dependsOnBean)){thrownewBeanCreationException("Circular depends-on relationship between '"+
beanName +"' and '"+ dependsOnBean +"'");}registerDependentBean(dependsOnBean, beanName);getBean(dependsOnBean);}}// Create bean instance.// 创建 bean 实例if(mbd.isSingleton()){// 从 singletonObjects 中获取 bean
sharedInstance =getSingleton(beanName,newObjectFactory<Object>(){@Overridepublic Object getObject()throws BeansException {try{returncreateBean(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);}elseif(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{
String scopeName = mbd.getScope();final Scope scope =this.scopes.get(scopeName);if(scope == null){thrownewIllegalStateException("No Scope registered for scope '"+ scopeName +"'");}try{
Object scopedInstance = scope.get(beanName,newObjectFactory<Object>(){@Overridepublic Object getObject()throws BeansException {beforePrototypeCreation(beanName);try{returncreateBean(beanName, mbd, args);}finally{afterPrototypeCreation(beanName);}}});
bean =getObjectForBeanInstance(scopedInstance, name, beanName, mbd);}catch(IllegalStateException ex){thrownewBeanCreationException(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;}}// Check if required type matches the type of the actual bean instance.if(requiredType != null && bean != null &&!requiredType.isAssignableFrom(bean.getClass())){try{returngetTypeConverter().convertIfNecessary(bean, requiredType);}catch(TypeMismatchException ex){if(logger.isDebugEnabled()){
logger.debug("Failed to convert bean '"+ name +"' to required type ["+
ClassUtils.getQualifiedName(requiredType)+"]", ex);}thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}}return(T) bean;}
5.1、getSingleton()
ublic 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){if(this.singletonsCurrentlyInDestruction){thrownewBeanCreationNotAllowedException(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 recordSuppressedExceptions =(this.suppressedExceptions == null);if(recordSuppressedExceptions){this.suppressedExceptions =newLinkedHashSet<Exception>();}try{// 利用反射创建 bean
singletonObject = singletonFactory.getObject();}catch(BeanCreationException ex){if(recordSuppressedExceptions){for(Exception suppressedException :this.suppressedExceptions){
ex.addRelatedCause(suppressedException);}}throw ex;}finally{if(recordSuppressedExceptions){this.suppressedExceptions = null;}afterSingletonCreation(beanName);}// 添加创建好的 bean 到 singletonObjectsaddSingleton(beanName, singletonObject);}return(singletonObject != NULL_OBJECT ? singletonObject : null);}}
5.2、创建好的对象最终会保存到一个 Map 中
// org.springframework.beans.factory.support.DefaultSingletonBeanRegistry/** Cache of singleton objects: bean name --> bean instance */// ioc 容器之一:保存单实例 bean 的地方// ioc 就是一个容器,单实例 bean 保存到一个 Map 中privatefinal Map<String, Object> singletonObjects =newConcurrentHashMap<String, Object>(64);
// doGetBean(name, null, null, false);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;// Eagerly check singleton cache for manually registered singletons.// 从已经创建的所有单实例 bean 中查看有没有这个 bean// 刚创建的时候没有,所以是 null,ioc 容器启动后在获取就不是 null 了,而是相应的 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 =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)){thrownewBeanCurrentlyInCreationException(beanName);}// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory =getParentBeanFactory();if(parentBeanFactory != null &&!containsBeanDefinition(beanName)){// Not found -> check parent.
String nameToLookup =originalBeanName(name);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);}}if(!typeCheckOnly){markBeanAsCreated(beanName);}try{final RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);checkMergedBeanDefinition(mbd, beanName, args);// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();if(dependsOn != null){for(String dependsOnBean : dependsOn){if(isDependent(beanName, dependsOnBean)){thrownewBeanCreationException("Circular depends-on relationship between '"+
beanName +"' and '"+ dependsOnBean +"'");}registerDependentBean(dependsOnBean, beanName);getBean(dependsOnBean);}}// Create bean instance.if(mbd.isSingleton()){
sharedInstance =getSingleton(beanName,newObjectFactory<Object>(){@Overridepublic Object getObject()throws BeansException {try{returncreateBean(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);}elseif(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{
String scopeName = mbd.getScope();final Scope scope =this.scopes.get(scopeName);if(scope == null){thrownewIllegalStateException("No Scope registered for scope '"+ scopeName +"'");}try{
Object scopedInstance = scope.get(beanName,newObjectFactory<Object>(){@Overridepublic Object getObject()throws BeansException {beforePrototypeCreation(beanName);try{returncreateBean(beanName, mbd, args);}finally{afterPrototypeCreation(beanName);}}});
bean =getObjectForBeanInstance(scopedInstance, name, beanName, mbd);}catch(IllegalStateException ex){thrownewBeanCreationException(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;}}// Check if required type matches the type of the actual bean instance.if(requiredType != null && bean != null &&!requiredType.isAssignableFrom(bean.getClass())){try{returngetTypeConverter().convertIfNecessary(bean, requiredType);}catch(TypeMismatchException ex){if(logger.isDebugEnabled()){
logger.debug("Failed to convert bean '"+ name +"' to required type ["+
ClassUtils.getQualifiedName(requiredType)+"]", ex);}thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}}return(T) bean;}