话不多说,先给出结论。本篇文章只谈论BeanPostProcessor
类的先后执行关系。
bean的具体实例化过程过于复杂,有兴趣了解的建议参考书籍《Spring源码深度分析》
org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization
org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors
org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference
org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation
org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessProperties
org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessPropertyValues(7执行后为null才执行8)
org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization
invokeInitMethods(扩展方法)
9.1 实现了InitializingBean接口的afterPropertiesSet()方法
9.2 调用initMethod()方法
org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization
扩展方法 处理实现DisposableBean接口
示例代码去掉日志以及一些与分析无关的
由于代码太多,所以只挑出关键代码,如果有兴趣,照着文章debug一遍即可明白流程。
org.springframework.beans.factory.support.AbstractBeanFactory#getBean(java.lang.String)
@OverridepublicObjectgetBean(Stringname)throwsBeansException{returndoGetBean(name,null,null,false);}
然后进入org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
protected<T>TdoGetBean(Stringname,@NullableClass<T>requiredType,@NullableObject[]args,booleantypeCheckOnly)throwsBeansException{StringbeanName=transformedBeanName(name);Objectbean;//Eagerlychecksingletoncacheformanuallyregisteredsingletons.ObjectsharedInstance=getSingleton(beanName);if(sharedInstance!=null&&args==null){bean=getObjectForBeanInstance(sharedInstance,name,beanName,null);}else{//循环依赖,会抛出异常if(isPrototypeCurrentlyInCreation(beanName)){thrownewBeanCurrentlyInCreationException(beanName);}//Checkifbeandefinitionexistsinthisfactory.BeanFactoryparentBeanFactory=getParentBeanFactory();····if(!typeCheckOnly){markBeanAsCreated(beanName);}try{RootBeanDefinitionmbd=getMergedLocalBeanDefinition(beanName);checkMergedBeanDefinition(mbd,beanName,args);···//Createbeaninstance.//创建bean实例,重点从这里开始分析if(mbd.isSingleton()){sharedInstance=getSingleton(beanName,()->{try{//重点代码在这里returncreateBean(beanName,mbd,args);}catch(BeansExceptionex){destroySingleton(beanName);throwex;}});bean=getObjectForBeanInstance(sharedInstance,name,beanName,mbd);}}//Checkifrequiredtypematchesthetypeoftheactualbeaninstance.if(requiredType!=null&&!requiredType.isInstance(bean)){try{TconvertedBean=getTypeConverter().convertIfNecessary(bean,requiredType);if(convertedBean==null){thrownewBeanNotOfRequiredTypeException(name,requiredType,bean.getClass());}returnconvertedBean;}catch(TypeMismatchExceptionex){thrownewBeanNotOfRequiredTypeException(name,requiredType,bean.getClass());}}return(T)bean;}
进入getSingleton()方法后,发现里面都是做一些准备工作,真正的调用是lambda表达式org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, org.springframework.beans.factory.ObjectFactory<?>)
publicObjectgetSingleton(StringbeanName,ObjectFactory<?>singletonFactory){synchronized(this.singletonObjects){ObjectsingletonObject=this.singletonObjects.get(beanName);if(singletonObject==null){if(this.singletonsCurrentlyInDestruction){thrownewBeanCreationNotAllowedException(beanName,"Singletonbeancreationnotallowedwhilesingletonsofthisfactoryareindestruction"+"(DonotrequestabeanfromaBeanFactoryinadestroymethodimplementation!)");}beforeSingletonCreation(beanName);booleannewSingleton=false;booleanrecordSuppressedExceptions=(this.suppressedExceptions==null);if(recordSuppressedExceptions){this.suppressedExceptions=newLinkedHashSet<>();}try{singletonObject=singletonFactory.getObject();newSingleton=true;}catch(IllegalStateExceptionex){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;}afterSingletonCreation(beanName);}if(newSingleton){addSingleton(beanName,singletonObject);}}returnsingletonObject;}}
第一二处
进入lambda表达式中org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])
protectedObjectcreateBean(StringbeanName,RootBeanDefinitionmbd,@NullableObject[]args)throwsBeanCreationException{RootBeanDefinitionmbdToUse=mbd;.Class<?>resolvedClass=resolveBeanClass(mbd,beanName);if(resolvedClass!=null&&!mbd.hasBeanClass()&&mbd.getBeanClassName()!=null){mbdToUse=newRootBeanDefinition(mbd);mbdToUse.setBeanClass(resolvedClass);}//Preparemethodoverrides.try{mbdToUse.prepareMethodOverrides();}catch(BeanDefinitionValidationExceptionex){thrownewBeanDefinitionStoreException(mbdToUse.getResourceDescription(),beanName,"Validationofmethodoverridesfailed",ex);}try{//实例化的前置处理,AOP功能就是基于这里判断的Objectbean=resolveBeforeInstantiation(beanName,mbdToUse);if(bean!=null){returnbean;}}catch(Throwableex){thrownewBeanCreationException(mbdToUse.getResourceDescription(),beanName,"BeanPostProcessorbeforeinstantiationofbeanfailed",ex);}try{ObjectbeanInstance=doCreateBean(beanName,mbdToUse,args);returnbeanInstance;}catch(BeanCreationException|ImplicitlyAppearedSingletonExceptionex){throwex;}catch(Throwableex){thrownewBeanCreationException(mbdToUse.getResourceDescription(),beanName,"Unexpectedexceptionduringbeancreation",ex);}}@NullableprotectedObjectresolveBeforeInstantiation(StringbeanName,RootBeanDefinitionmbd){Objectbean=null;if(!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)){//Makesurebeanclassisactuallyresolvedatthispoint.if(!mbd.isSynthetic()&&hasInstantiationAwareBeanPostProcessors()){Class<?>targetType=determineTargetType(beanName,mbd);if(targetType!=null){//第一处bean=applyBeanPostProcessorsBeforeInstantiation(targetType,beanName);if(bean!=null){//第二处bean=applyBeanPostProcessorsAfterInitialization(bean,beanName);}}}mbd.beforeInstantiationResolved=(bean!=null);}returnbean;}
第三处
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance
protectedBeanWrappercreateBeanInstance(StringbeanName,RootBeanDefinitionmbd,@NullableObject[]args){//Candidateconstructorsforautowiring?Constructor<?>[]ctors=determineConstructorsFromBeanPostProcessors(beanClass,beanName);···}protectedConstructor<?>[]determineConstructorsFromBeanPostProcessors(@NullableClass<?>beanClass,StringbeanName)throwsBeansException{if(beanClass!=null&&hasInstantiationAwareBeanPostProcessors()){for(BeanPostProcessorbp:getBeanPostProcessors()){if(bpinstanceofSmartInstantiationAwareBeanPostProcessor){SmartInstantiationAwareBeanPostProcessoribp=(SmartInstantiationAwareBeanPostProcessor)bp;Constructor<?>[]ctors=ibp.determineCandidateConstructors(beanClass,beanName);if(ctors!=null){returnctors;}}}}returnnull;}
第四五、十一处
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
protectedObjectdoCreateBean(StringbeanName,RootBeanDefinitionmbd,@NullableObject[]args)throwsBeanCreationException{···synchronized(mbd.postProcessingLock){if(!mbd.postProcessed){try{//第4处applyMergedBeanDefinitionPostProcessors(mbd,beanType,beanName);}catch(Throwableex){thrownewBeanCreationException(mbd.getResourceDescription(),beanName,"Post-processingofmergedbeandefinitionfailed",ex);}mbd.postProcessed=true;}}booleanearlySingletonExposure=(mbd.isSingleton()&&this.allowCircularReferences&&isSingletonCurrentlyInCreation(beanName));if(earlySingletonExposure){if(logger.isTraceEnabled()){logger.trace("Eagerlycachingbean'"+beanName+"'toallowforresolvingpotentialcircularreferences");}//第五处lambda表达式addSingletonFactory(beanName,()->getEarlyBeanReference(beanName,mbd,bean));}···try{//第11处Registerbeanasdisposable.registerDisposableBeanIfNecessary(beanName,bean,mbd);}returnexposedObject;}//第五处lambda表达式protectedObjectgetEarlyBeanReference(StringbeanName,RootBeanDefinitionmbd,Objectbean){ObjectexposedObject=bean;if(!mbd.isSynthetic()&&hasInstantiationAwareBeanPostProcessors()){for(BeanPostProcessorbp:getBeanPostProcessors()){if(bpinstanceofSmartInstantiationAwareBeanPostProcessor){SmartInstantiationAwareBeanPostProcessoribp=(SmartInstantiationAwareBeanPostProcessor)bp;exposedObject=ibp.getEarlyBeanReference(exposedObject,beanName);}}}returnexposedObject;}
第六七八处
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean
protectedvoidpopulateBean(StringbeanName,RootBeanDefinitionmbd,@NullableBeanWrapperbw){···if(!mbd.isSynthetic()&&hasInstantiationAwareBeanPostProcessors()){for(BeanPostProcessorbp:getBeanPostProcessors()){if(bpinstanceofInstantiationAwareBeanPostProcessor){InstantiationAwareBeanPostProcessoribp=(InstantiationAwareBeanPostProcessor)bp;//第六处if(!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(),beanName)){return;}}}}PropertyDescriptor[]filteredPds=null;if(hasInstAwareBpps){if(pvs==null){pvs=mbd.getPropertyValues();}for(BeanPostProcessorbp:getBeanPostProcessors()){if(bpinstanceofInstantiationAwareBeanPostProcessor){InstantiationAwareBeanPostProcessoribp=(InstantiationAwareBeanPostProcessor)bp;//第7处PropertyValuespvsToUse=ibp.postProcessProperties(pvs,bw.getWrappedInstance(),beanName);if(pvsToUse==null){if(filteredPds==null){filteredPds=filterPropertyDescriptorsForDependencyCheck(bw,mbd.allowCaching);}//第8处pvsToUse=ibp.postProcessPropertyValues(pvs,filteredPds,bw.getWrappedInstance(),beanName);if(pvsToUse==null){return;}}pvs=pvsToUse;}}}
第九十处
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)
protectedObjectinitializeBean(StringbeanName,Objectbean,@NullableRootBeanDefinitionmbd){if(System.getSecurityManager()!=null){AccessController.doPrivileged((PrivilegedAction<Object>)()->{invokeAwareMethods(beanName,bean);returnnull;},getAccessControlContext());}else{//处理实现了aware的接口,设置beanname或者工厂invokeAwareMethods(beanName,bean);}ObjectwrappedBean=bean;if(mbd==null||!mbd.isSynthetic()){//第九处wrappedBean=applyBeanPostProcessorsBeforeInitialization(wrappedBean,beanName);}try{invokeInitMethods(beanName,wrappedBean,mbd);}catch(Throwableex){thrownewBeanCreationException((mbd!=null?mbd.getResourceDescription():null),beanName,"Invocationofinitmethodfailed",ex);}if(mbd==null||!mbd.isSynthetic()){//第10处wrappedBean=applyBeanPostProcessorsAfterInitialization(wrappedBean,beanName);}returnwrappedBean;}//Spring初始化扩展方法protectedvoidinvokeInitMethods(StringbeanName,Objectbean,@NullableRootBeanDefinitionmbd)throwsThrowable{booleanisInitializingBean=(beaninstanceofInitializingBean);if(isInitializingBean&&(mbd==null||!mbd.isExternallyManagedInitMethod("afterPropertiesSet"))){if(logger.isTraceEnabled()){logger.trace("InvokingafterPropertiesSet()onbeanwithname'"+beanName+"'");}if(System.getSecurityManager()!=null){try{AccessController.doPrivileged((PrivilegedExceptionAction<Object>)()->{((InitializingBean)bean).afterPropertiesSet();returnnull;},getAccessControlContext());}catch(PrivilegedActionExceptionpae){throwpae.getException();}}else{((InitializingBean)bean).afterPropertiesSet();}}\if(mbd!=null&&bean.getClass()!=NullBean.class){StringinitMethodName=mbd.getInitMethodName();if(StringUtils.hasLength(initMethodName)&&!(isInitializingBean&&"afterPropertiesSet".equals(initMethodName))&&!mbd.isExternallyManagedInitMethod(initMethodName)){invokeCustomInitMethod(beanName,bean,mbd);}}}