你知道Springboot启动过程中的这个BeanPostProcessor是干什么的吗?该函数从这里开始创建一个Bean实例。1环境准备@ComponentpublicclassPersonDAOImplimplementsPersonDAO{@Overridepublicvoidsave(){System.out.println("保存人员信息");}}@ServicepublicclassUsersService{@AutowiredprivatePersonDAOpersonDAO;publicvoidsaveUsers(Usersusers){System.out.println("保存用户信息");}}2创建实例publicabstractclassAbstractAutowireCapableBeanFactory{protectedObjectdoCreateBean(StringbeanName,RootBeanDefinitionmbd,@NullableObject[]args){BeanWrapperinstanceWrapper=null;if(instanceWrapper==null){instanceWrapper=createBeanInstance(beanName,mbd,rootBeanDefinitionmbd,@NullableObject[]args);}/synchronized(mbd.postProcessingLock){if(!mbd.postProcessed){try{//创建实例后调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法applyMergedBeanDefinitionPostProcessors(mbd,beanType,beanName);}catch(Throwableex){}mbd.postProcessed=true}}}}3执行合并Bean定义方法publicabstractclassAbstractAutowireCapableBeanFactory{protectedvoidapplyMergedBeanDefinitionPostProcessors(RootBeanDefinitionmbd,Class>beanType,StringbeanName){for(BeanPostProcessorbp:getBeanPostProcessors()){if(bpinstanceofMergedBeanDefinitionPostProcessor){MergedBeanDefinitionPostProcessordp=(MergedBeanDefinitionPostProcessor)bp;bdp.postProcessMergedBeanDefinition(mband在,bean}里}里,需要的BeanPostProcessor对象有:CommonAnnotationBeanPostProcessor和AutowiredAnnotationBeanPostProcessor(这里列出了两个键值)Common主要处理相关的注解如@PostConstruct、@PreDestroy和@Resource;Autowired主要处理:@Autowired和@Value以及@InjectAnnotation在上面准备好的类中,PersonDAO对象是通过@Autowired注入到UserService中的,所以这里主要看AutowiredAnnotationBeanPostProcessor处理器4处理执行publicclassAutowiredAnnotationBeanPostProcessor{privatefinalMapinjectionMetadataCache=newConcurrentHashMap<>(256);privatefinalSet>autowiredAnnotationTypes=newLinkedHashSet<>(4);publicAutowiredAnnotationBeanPostProcessautowired.notation.Autowired.notation.);this.autowiredAnnotationTypes.add(Value.class);try{this.autowiredAnnotationTypes.add((Class)ClassUtils.forName("javax.inject.Inject",AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));logger.trace("JSR-330'javax.inject.Inject'annotationfoundandsupportedforautowiring");}catch(ClassNotFoundExceptionex){//JSR-330APInotavailable-simplyskip.}}publicvoidpostProcessMergedBeanDefinition(RootBeanDefinitionbeanDefinition,Class>beanType,StringbeanName){//查找InjectionMetadatametadata=findAutowiringMetadata(beanName,beanType,null);metadata.checkConfigMembers(beanDefinition);}privateInjectionMetadatafindAutowiringMetadata(StringbeanName,Class>clazz,@NullablePropertyValuespvs){//Fallbacktoclassnameascachekey,forwardscompatibilitywithcustomcallers.//生成缓存使用的Key名称,然后使用Key缓存相应信息StringcacheKey=(StringUtils.hasLength(beanName)?beanName:clazz.getName());//从当前cache中获取InjectionMetadata是否存在metadata=this.injectionMetadataCache.get(cacheKey);//该方法会判断缓存是否存在,上面的metadata;以下是通过if(InjectionMetadata.needsRefresh(metadata,clazz)){synchronized(this.injectionMetadataCache){metadata=this.injectionMetadataCache.get(cacheKey);if(InjectionMetadata.needsRefresh(metadata,clazz)){if(metadata!=null){metadata.clear(pvs);}//构建自动装配元信息;这里通过当前处理的类对象查找是否有@Autowired注解信息(从字段和方法中查找).this.injectionMetadataCache.put(cacheKey,metadata);}}}returnmetadata;}privateInjectionMetadatabuildAutowiringMetadata(finalClass<?>clazz){if(!AnnotationUtils.isCandidateClass(clazz,this.autowiredAnnotationTypes)){returnInjectionMetadata.EMPTY;}Listelements=newArrayList<>();Class>targetClass=clazz;做{finalListcurrElements=newArrayList<>();//这里通过方法也可以知道遍历当前类中的所有字段,检查是否有@Autowired注解ReflectionUtils.doWithLocalFields(targetClass,field->{//在字段上查找@Autowired注解信息MergedAnnotation>ann=findAutowiredAnnotation(field);if(ann!=null){//判断当前字段是否被staticif(Modifier.isStatic(field.getModifiers())){return;}//判断字段是否必填(默认为true,注入的Bean必须存在)booleanrequired=determineRequiredStatus(ann);//将找到的字段信息保存到AutowriedFieldElementcurrElements.add(newAutowiredFieldElement(field,required));}});//遍历所有方法s在当前类中,是否有@Autowired注解信息yBridgeMethodPair(方法,bridgedMethod)){return;}MergedAnnotation>ann=findAutowiredAnnotation(bridgedMethod);if(ann!=null&&method.equals(ClassUtils.getMostSpecificMethod(method,clazz))){if(Modifier.isStatic(method.getModifiers())){return;}booleanrequired=determineRequiredStatus(ann);PropertyDescriptorpd=BeanUtils.findPropertyForMethod(bridgedMethod,clazz);currElements.add(newAutowiredMethodElement(method,required,pd));}});elements.addAll(0,当前元素);targetClass=targetClass.getSuperclass();//遍历当前类和父类,直到父类为Object}while(targetClass!=null&&targetClass!=Object.class);returnInjectionMetadata.forElements(elements,clazz);}@NullableprivateMergedAnnotation>findAutowiredAnnotation(AccessibleObjectao){MergedAnnotationsannotations=MergedAnnotations.from(ao);//开始遍历autowiredAnnotationTypes集合中是否有在当前字段(方法)上定义的注解(该集合是在对象刚添加时构造的)for(Classtype:this.autowiredAnnotationTypes){MergedAnnotation>annotation=annotations.get(type);if(annotation.isPresent()){returnannotation;}}returnnull;}}publicabstractclassReflectionUtils{publicstaticvoiddoWithLocalFields(Class>clazz,FieldCallbackfc){for(Fieldfield:getDeclaredFields(clazz)){try{fc.doWith(field);}catch(IllegalAccessExceptionex){thrownewIllegalStateException("Notallowedtoaccessfield'"+field.getName()+"':"+ex);}}}publicstaticvoiddoWithLocalMethods(Class>clazz,MethodCallbackmc){Method[]methods=getDeclaredMethods(clazz,false);for(Methodmethod:methods){try{mc.doWith(method);}catch(IllegalAccessExceptionex){thrownewIllegalStateException("Noallowedtoaccessmethod'"+method.getName()+"':"+ex);}}}}5这里的属性填充会使用上面缓存中的值来注入属性publicclassAutowiredAnnotationBeanPostProcessor{publicPropertyValuespostProcessProperties(PropertyValuespvs,Objectbean,StringbeanName){//这里会直接从缓存中获取(injectionMetadataCache)getInjectionMetadatametadata=findAutowiringMetadata(beanName,bean.getClass(),pvs);//属性的填充注入metadata.inject(bean,beanName,pvs);returnpvs;}privateInjectionMetadatafindAutowiringMetadata(StringbeanName,Class>clazz,@NullablePropertyValuespvs){//Fallbacktoclassnameascachekey,forbackwardscompatibilitywithcustomcallers.StringcacheKey=(StringUtils.hasLength(beanName)?beanName:clazz.getName());//Quickcheckontheconcurrentmapfirst,withminimallocking.InjectionMetadatametadata=this.injectionMetadataCache.get(cacheKey);if(InjectionMetadata.needsRefresh(metadata,clazz)){同步(this.injectionMetadataCache){metadata=this.injectionMetadataCache.get(cacheKey);if(InjectionMetadata.needsRefresh(metadata,clazz)){if(metadata!=null){metadata.clear(pvs);}metadata=buildAutowiringMetadata(clazz);this.injectionMetadataCache.put(cacheKey,metadata);}}}returnmetadata;}}以上就是MergedBeanDefinitionPostProcessor处理器的作用了