SpringIOC refresh()初始化代码实例
finishBeanFactoryInitialization(beanFactory):初始化不需要延迟实例化的单例bean
/*org/springframework/context/support/AbstractApplicationContext.java:870*/ protectedvoidfinishBeanFactoryInitialization(ConfigurableListableBeanFactorybeanFactory){//初始化容器的conversionService 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)); } //如果没有任何一个类似PropertyPlaceholderConfigurerbean处理器 //默认一个嵌入式值解析器,主要是为了解析属性值例如数据库连接中${password}等属性解析 if(!beanFactory.hasEmbeddedValueResolver()){ beanFactory.addEmbeddedValueResolver(strVal->getEnvironment().resolvePlaceholders(strVal)); } //先实例化LoadTimeWeaverAware相关的beans,以便尽早转换,AOP相关 String[]weaverAwareNames=beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class,false,false); for(StringweaverAwareName:weaverAwareNames){ getBean(weaverAwareName); } //删除临时类加载器,停止临时类加载器进行类型匹配 beanFactory.setTempClassLoader(null); //拷贝beandefinitionNames到frozenBeanDefinitionNames beanFactory.freezeConfiguration(); //实例化所有不需要延迟初始化的单例bean beanFactory.preInstantiateSingletons(); }
beanFactory.preInstantiateSingletons():实例化所有不需要延迟初始化的单例bean
/*org/springframework/beans/factory/support/DefaultListableBeanFactory.java:885*/ publicvoidpreInstantiateSingletons()throwsBeansException{ if(logger.isTraceEnabled()){ logger.trace("Pre-instantiatingsingletonsin"+this); } //Iterateoveracopytoallowforinitmethodswhichinturnregisternewbeandefinitions. //Whilethismaynotbepartoftheregularfactorybootstrap,itdoesotherwiseworkfine. //拷贝beanDefinitionNames副本,考虑到遍历中其他线程可能修改beandefinitionNames //ArrayList类型遍历时规避fast-fail,实现fast-safe ListbeanNames=newArrayList<>(this.beanDefinitionNames); //Triggerinitializationofallnon-lazysingletonbeans... for(StringbeanName:beanNames){ //当bean存在parentBean时的继承关系 //①bean不存在parentBean时,创建一个newRootBeanDefinition(beandefinition)返回。 //②bean存在parentBean时,支持继承关系 //需要先创建parentBean的newRootBeanDefinition(parentBeanDefinition) //然后用beandefinition覆盖parentBean的RootBeanDefinition的相关属性并返回。superBean.overrideFrom(subBean); RootBeanDefinitionbd=getMergedLocalBeanDefinition(beanName); //用mergedLocalBeanDefinition判断是否需要初始化 //筛选不是抽象类且不是延迟实例化的单例进行初始化 if(!bd.isAbstract()&&bd.isSingleton()&&!bd.isLazyInit()){ if(isFactoryBean(beanName)){ //工厂BeanbeanName=&beanName Objectbean=getBean(FACTORY_BEAN_PREFIX+beanName); if(beaninstanceofFactoryBean){ finalFactoryBean>factory=(FactoryBean>)bean; booleanisEagerInit; if(System.getSecurityManager()!=null&&factoryinstanceofSmartFactoryBean){ isEagerInit=AccessController.doPrivileged((PrivilegedAction ) ((SmartFactoryBean>)factory)::isEagerInit, getAccessControlContext()); } else{ isEagerInit=(factoryinstanceofSmartFactoryBean&& ((SmartFactoryBean>)factory).isEagerInit()); } if(isEagerInit){ getBean(beanName); } } } else{ //不是工厂bean直接初始化 getBean(beanName); } } } //SmartInitializingSingleton类型的单例初始化后的回调 for(StringbeanName:beanNames){ ObjectsingletonInstance=getSingleton(beanName); if(singletonInstanceinstanceofSmartInitializingSingleton){ finalSmartInitializingSingletonsmartSingleton=(SmartInitializingSingleton)singletonInstance; if(System.getSecurityManager()!=null){ AccessController.doPrivileged((PrivilegedAction
getBean(beanName):Bean初始化
/*org/springframework/beans/factory/support/AbstractBeanFactory.java:414*/ protectedTdoGetBean(finalStringname,@NullablefinalClass requiredType, @NullablefinalObject[]args,booleantypeCheckOnly)throwsBeansException{ //如果是aliaName,解析成beanName finalStringbeanName=transformedBeanName(name); Objectbean; //Eagerlychecksingletoncacheformanuallyregisteredsingletons. //检查单例缓存中是否存在bean的实例化对象、初始化对象(涉及循环依赖解决,需要先分清出Bean的两个阶段实例化、初始化) ObjectsharedInstance=getSingleton(beanName); if(sharedInstance!=null&&args==null){ if(logger.isTraceEnabled()){ if(isSingletonCurrentlyInCreation(beanName)){ logger.trace("Returningeagerlycachedinstanceofsingletonbean'"+beanName+ "'thatisnotfullyinitializedyet-aconsequenceofacircularreference"); } else{ logger.trace("Returningcachedinstanceofsingletonbean'"+beanName+"'"); } } bean=getObjectForBeanInstance(sharedInstance,name,beanName,null); } else{ if(isPrototypeCurrentlyInCreation(beanName)){ //多例bean正在初始化时抛出异常 //由于多例bean,每调用一次getBean就会创建一个实例, //所以通过ThreadLocal打标,来避免单个线程的重复创建 thrownewBeanCurrentlyInCreationException(beanName); } BeanFactoryparentBeanFactory=getParentBeanFactory(); //父容器不为空,用父容器初始化 if(parentBeanFactory!=null&&!containsBeanDefinition(beanName)){ //Notfound->checkparent. StringnameToLookup=originalBeanName(name); if(parentBeanFactoryinstanceofAbstractBeanFactory){ return((AbstractBeanFactory)parentBeanFactory).doGetBean( nameToLookup,requiredType,args,typeCheckOnly); } elseif(args!=null){ //Delegationtoparentwithexplicitargs. return(T)parentBeanFactory.getBean(nameToLookup,args); } elseif(requiredType!=null){ //Noargs->delegatetostandardgetBeanmethod. returnparentBeanFactory.getBean(nameToLookup,requiredType); } else{ return(T)parentBeanFactory.getBean(nameToLookup); } } if(!typeCheckOnly){ //alreadyCreated容器记录已经被实例化的beanName, //这里将beanName添加到alreadyCreated markBeanAsCreated(beanName); } try{ //重新获取mergedLocalBeanDefinition(bean与parentBean合并) finalRootBeanDefinitionmbd=getMergedLocalBeanDefinition(beanName); //检查mbd不是抽象类 checkMergedBeanDefinition(mbd,beanName,args); //创建bean单例之前,需要保证先bean所依赖的Bean单例已创建, //这里的依赖对应@dependsOn声明的依赖,这个注解不常用,这里也会出现一种循环依赖场景,与我们平常讨论的引用循环依赖不同 //@dependsOn(value="b")classA;@dependsOn(value="a")classB //如果出现这种循环依赖会直接抛出异常启动失败 String[]dependsOn=mbd.getDependsOn(); if(dependsOn!=null){ for(Stringdep:dependsOn){ if(isDependent(beanName,dep)){ thrownewBeanCreationException(mbd.getResourceDescription(),beanName, "Circulardepends-onrelationshipbetween'"+beanName+"'and'"+dep+"'"); } //保存依赖关系到dependentBeanMap容器中 registerDependentBean(dep,beanName); try{ //实例化依赖的bean这里就是常见循环依赖地点A依赖BB依赖A getBean(dep); } catch(NoSuchBeanDefinitionExceptionex){ thrownewBeanCreationException(mbd.getResourceDescription(),beanName, "'"+beanName+"'dependsonmissingbean'"+dep+"'",ex); } } } //Createbeaninstance. if(mbd.isSingleton()){ //单例Bean创建先取缓存,没有才createBean sharedInstance=getSingleton(beanName,()->{ try{ //创建Bean实例 returncreateBean(beanName,mbd,args); } catch(BeansExceptionex){ destroySingleton(beanName); throwex; } }); bean=getObjectForBeanInstance(sharedInstance,name,beanName,mbd); } elseif(mbd.isPrototype()){ //多例Bean创建直接createbean ObjectprototypeInstance=null; try{ //正在创建bean打标prototypesCurrentlyInCreation //与上面isPrototypeCurrentlyInCreation()联合 beforePrototypeCreation(beanName); prototypeInstance=createBean(beanName,mbd,args); } finally{ //正在创建bean打标prototypesCurrentlyInCreation删除标记 afterPrototypeCreation(beanName); } bean=getObjectForBeanInstance(prototypeInstance,name,beanName,mbd); } else{ //自定义scope初始化、scope.get() StringscopeName=mbd.getScope(); finalScopescope=this.scopes.get(scopeName); if(scope==null){ thrownewIllegalStateException("NoScoperegisteredforscopename'"+scopeName+"'"); } try{ ObjectscopedInstance=scope.get(beanName,()->{ beforePrototypeCreation(beanName); try{ returncreateBean(beanName,mbd,args); } finally{ afterPrototypeCreation(beanName); } }); bean=getObjectForBeanInstance(scopedInstance,name,beanName,mbd); } catch(IllegalStateExceptionex){ thrownewBeanCreationException(beanName, "Scope'"+scopeName+"'isnotactiveforthecurrentthread;consider"+ "definingascopedproxyforthisbeanifyouintendtorefertoitfromasingleton", ex); } } } catch(BeansExceptionex){ cleanupAfterBeanCreationFailure(beanName); throwex; } } //getBean(beanName,requiredType)时检查创建的实例是否需要的类型,容器初始化时不会走进里面 if(requiredType!=null&&!requiredType.isInstance(bean)){ try{ TconvertedBean=getTypeConverter().convertIfNecessary(bean,requiredType); if(convertedBean==null){ thrownewBeanNotOfRequiredTypeException(name,requiredType,bean.getClass()); } returnconvertedBean; } catch(TypeMismatchExceptionex){ if(logger.isTraceEnabled()){ logger.trace("Failedtoconvertbean'"+name+"'torequiredtype'"+ ClassUtils.getQualifiedName(requiredType)+"'",ex); } thrownewBeanNotOfRequiredTypeException(name,requiredType,bean.getClass()); } } return(T)bean; }
sharedInstance=getSingleton(beanName,()->{try{returncreateBean(beanName,mbd,args);}:单例初始化,这个方法比较简单,主要关注下和循坏依赖相关的逻辑
/*org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java:201*/ publicObjectgetSingleton(StringbeanName,ObjectFactory>singletonFactory){ Assert.notNull(beanName,"Beannamemustnotbenull"); synchronized(this.singletonObjects){ ObjectsingletonObject=this.singletonObjects.get(beanName); if(singletonObject==null){ if(this.singletonsCurrentlyInDestruction){ thrownewBeanCreationNotAllowedException(beanName, "Singletonbeancreationnotallowedwhilesingletonsofthisfactoryareindestruction"+ "(DonotrequestabeanfromaBeanFactoryinadestroymethodimplementation!)"); } if(logger.isDebugEnabled()){ logger.debug("Creatingsharedinstanceofsingletonbean'"+beanName+"'"); } //循环依赖相关:初始化前先singletonsCurrentlyInCreation.add(beanName) beforeSingletonCreation(beanName); booleannewSingleton=false; booleanrecordSuppressedExceptions=(this.suppressedExceptions==null); if(recordSuppressedExceptions){ this.suppressedExceptions=newLinkedHashSet<>(); } try{ //lamda表达式:其实是调用createBean(beanName,mbd,args):Bean初始化 singletonObject=singletonFactory.getObject(); newSingleton=true; } catch(IllegalStateExceptionex){ //Hasthesingletonobjectimplicitlyappearedinthemeantime-> //ifyes,proceedwithitsincetheexceptionindicatesthatstate. singletonObject=this.singletonObjects.get(beanName); if(singletonObject==null){ throwex; } } catch(BeanCreationExceptionex){ if(recordSuppressedExceptions){ for(ExceptionsuppressedException:this.suppressedExceptions){ ex.addRelatedCause(suppressedException); } } throwex; } finally{ if(recordSuppressedExceptions){ this.suppressedExceptions=null; } //循环依赖相关:初始化后singletonsCurrentlyInCreation.remove(beanName) afterSingletonCreation(beanName); } if(newSingleton){ //初始化完后 //this.singletonObjects.put(beanName,singletonObject);放入到单例容器中 //this.singletonFactories.remove(beanName);清空循环依赖相关的两个打标 //this.earlySingletonObjects.remove(beanName); //this.registeredSingletons.add(beanName);放入单例beanName容器中 addSingleton(beanName,singletonObject); } } returnsingletonObject; } }
createBean(beanName,mbd,args):初始化实例,这个表方法注意一下,初始化实例前,留机会给BeanPostProcessor初始化代理类直接返回代理类初始化实例
/*org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java:467*/ protectedObjectcreateBean(StringbeanName,RootBeanDefinitionmbd,@NullableObject[]args) throwsBeanCreationException{ if(logger.isTraceEnabled()){ logger.trace("Creatinginstanceofbean'"+beanName+"'"); } RootBeanDefinitionmbdToUse=mbd; Class>resolvedClass=resolveBeanClass(mbd,beanName); if(resolvedClass!=null&&!mbd.hasBeanClass()&&mbd.getBeanClassName()!=null){ //确保beanclass确实被解析了,若合并出错,重新定义bean定义 mbdToUse=newRootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); } //Preparemethodoverrides. try{ //校验需要重写方法是否全部重写,并且会给重写方法是否重载打标 mbdToUse.prepareMethodOverrides(); } catch(BeanDefinitionValidationExceptionex){ thrownewBeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName,"Validationofmethodoverridesfailed",ex); } try{ //resolveBeforeInstantiation方法是调用BeanPostProcessor处理器 //后续研究一下BeanPostProcessor //这里是给AOP相关BeanPostProcessor处理器生成代理类实例的机会,直接生成初始化代理类实例返回 //会面研究AOP时发现,proxyobject不是在这里初始化,这里只是提供一个机会 //proxyobject具体是在的下面doCreateBean时里先创建targetobject //然后通过后置处理器的后置方法初始化的 Objectbean=resolveBeforeInstantiation(beanName,mbdToUse); if(bean!=null){ returnbean; } } catch(Throwableex){ thrownewBeanCreationException(mbdToUse.getResourceDescription(),beanName, "BeanPostProcessorbeforeinstantiationofbeanfailed",ex); } try{ //初始化实例 ObjectbeanInstance=doCreateBean(beanName,mbdToUse,args); if(logger.isTraceEnabled()){ logger.trace("Finishedcreatinginstanceofbean'"+beanName+"'"); } returnbeanInstance; } catch(BeanCreationException|ImplicitlyAppearedSingletonExceptionex){ //Apreviouslydetectedexceptionwithproperbeancreationcontextalready, //orillegalsingletonstatetobecommunicateduptoDefaultSingletonBeanRegistry. throwex; } catch(Throwableex){ thrownewBeanCreationException( mbdToUse.getResourceDescription(),beanName,"Unexpectedexceptionduringbeancreation",ex); } }
doCreateBean(beanName,mbdToUse,args):beanClass实例化(即earlysingleton,注意不是初始化)然后DI完成初始化
/*org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java:549*/ protectedObjectdoCreateBean(finalStringbeanName,finalRootBeanDefinitionmbd,final@NullableObject[]args) throwsBeanCreationException{ //Instantiatethebean. BeanWrapperinstanceWrapper=null; if(mbd.isSingleton()){ instanceWrapper=this.factoryBeanInstanceCache.remove(beanName); } if(instanceWrapper==null){ //反射调用beanClass的构造方法创建实例并包装成beanwrapper-- instanceWrapper=createBeanInstance(beanName,mbd,args); } finalObjectbean=instanceWrapper.getWrappedInstance(); Class>beanType=instanceWrapper.getWrappedClass(); if(beanType!=NullBean.class){ mbd.resolvedTargetType=beanType; } //Allowpost-processorstomodifythemergedbeandefinition. //允许MergedBeanDefinitionPostProcessors后置管理器修改rootBeandefinition synchronized(mbd.postProcessingLock){ if(!mbd.postProcessed){ try{ applyMergedBeanDefinitionPostProcessors(mbd,beanType,beanName); } catch(Throwableex){ thrownewBeanCreationException(mbd.getResourceDescription(),beanName, "Post-processingofmergedbeandefinitionfailed",ex); } mbd.postProcessed=true; } } //Eagerlycachesingletonstobeabletoresolvecircularreferences //evenwhentriggeredbylifecycleinterfaceslikeBeanFactoryAware. booleanearlySingletonExposure=(mbd.isSingleton()&&this.allowCircularReferences&& isSingletonCurrentlyInCreation(beanName)); if(earlySingletonExposure){ if(logger.isTraceEnabled()){ logger.trace("Eagerlycachingbean'"+beanName+ "'toallowforresolvingpotentialcircularreferences"); } //循环依赖相关逻辑: //this.singletonFactories.put(beanName,singletonFactory); //将实例化bean、beanName组装成singletonFactory装入singletonFactories容器 //this.earlySingletonObjects.remove(beanName); //删除earlySingletonObjects中beanName addSingletonFactory(beanName,()->getEarlyBeanReference(beanName,mbd,bean)); } //Initializethebeaninstance. //创建实例 ObjectexposedObject=bean; try{ //实例初始化就是在这里面实现依赖注入DI的: //具体是调用AutowiredAnnotationBeanPostProcessor.postProcessProperties populateBean(beanName,mbd,instanceWrapper);//调用Bean后置管理器前置方法BeanPostProcessor.postProcessBeforeInitialization //instanceofaware接口,setBeanNamesetBeanClassLoadersetBeanFactory //调用Bean后置管理器后置方法BeanPostProcessor.postProcessAfterInitialization exposedObject=initializeBean(beanName,exposedObject,mbd); } catch(Throwableex){ if(exinstanceofBeanCreationException&&beanName.equals(((BeanCreationException)ex).getBeanName())){ throw(BeanCreationException)ex; } else{ thrownewBeanCreationException( mbd.getResourceDescription(),beanName,"Initializationofbeanfailed",ex); } } //... returnexposedObject; }
populateBean(beanName,mbd,instanceWrapper):依赖注入DI执行时机
/*org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java:1381*/ protectedvoidpopulateBean(StringbeanName,RootBeanDefinitionmbd,@NullableBeanWrapperbw){ //... PropertyDescriptor[]filteredPds=null; if(hasInstAwareBpps){ if(pvs==null){ pvs=mbd.getPropertyValues(); } for(BeanPostProcessorbp:getBeanPostProcessors()){ if(bpinstanceofInstantiationAwareBeanPostProcessor){ InstantiationAwareBeanPostProcessoribp=(InstantiationAwareBeanPostProcessor)bp; //这里调用AutowiredAnnotationBeanPostProcessor.postProcessProperties() //完成注解自动注入(DI) PropertyValuespvsToUse=ibp.postProcessProperties(pvs,bw.getWrappedInstance(),beanName); if(pvsToUse==null){ if(filteredPds==null){ filteredPds=filterPropertyDescriptorsForDependencyCheck(bw,mbd.allowCaching); } pvsToUse=ibp.postProcessPropertyValues(pvs,filteredPds,bw.getWrappedInstance(),beanName); if(pvsToUse==null){ return; } } pvs=pvsToUse; } } } if(needsDepCheck){ if(filteredPds==null){ filteredPds=filterPropertyDescriptorsForDependencyCheck(bw,mbd.allowCaching); } checkDependencies(beanName,mbd,filteredPds,pvs); } if(pvs!=null){ applyPropertyValues(beanName,mbd,bw,pvs); } }
DI结束,bean初始化基本结束了。然后就是bean初始化的BeanPostProcessor执行前置后置方法
BeanPostProcessor前置后置方法:一些很重要架构都需要依靠实现,例如AOP动态代理产生代理对象
AnnotationAwareAspectJAutoProxyCreator.postProcessAfterInitialization
/*org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String,java.lang.Object,org.springframework.beans.factory.support.RootBeanDefinition)*/ protectedObjectinitializeBean(finalStringbeanName,finalObjectbean,@NullableRootBeanDefinitionmbd){ if(System.getSecurityManager()!=null){ AccessController.doPrivileged((PrivilegedAction
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。