前言
前面对Spring IOC的源码进行了分析,主要是针对Spring IOC的整体源码流程进行分析,并没有涉及到太多细节部分。接下来,会对Spring IOC的内置后置处理器的源码进行分析总结。Spring中的内置处理器有两类,即Bean的后置处理器和BeanFactory的后置处理器,本篇将会对这两类的后置处理器进行一个总结分析。
invokeBeanFactoryPostProcessors
这里会获取两处存储BeanFactoryPostProcessor的对象,传入供接下来的调用,1.当前Bean工厂,2.和我们自己调用addBeanFactoryPostProcessor的自定义BeanFactoryPostProcessor。
publicstaticvoidinvokeBeanFactoryPostProcessors(ConfigurableListableBeanFactorybeanFactory,List<BeanFactoryPostProcessor>beanFactoryPostProcessors){//调用BeanDefinitionRegistryPostProcessor的后置处理器Begin//定义已处理的后置处理器Set<String>processedBeans=newHashSet<>();//判断我们的beanFactory实现了BeanDefinitionRegistry(实现了该结构就有注册和获取Bean定义的能力)if(beanFactoryinstanceofBeanDefinitionRegistry){//强行把我们的bean工厂转为BeanDefinitionRegistry,因为待会需要注册Bean定义BeanDefinitionRegistryregistry=(BeanDefinitionRegistry)beanFactory;//保存BeanFactoryPostProcessor类型的后置BeanFactoryPostProcessor提供修改List<BeanFactoryPostProcessor>regularPostProcessors=newArrayList<>();//保存BeanDefinitionRegistryPostProcessor类型的后置处理器BeanDefinitionRegistryPostProcessor提供注册List<BeanDefinitionRegistryPostProcessor>registryProcessors=newArrayList<>();//循环我们传递进来的beanFactoryPostProcessorsfor(BeanFactoryPostProcessorpostProcessor:beanFactoryPostProcessors){//判断我们的后置处理器是不是BeanDefinitionRegistryPostProcessorif(postProcessorinstanceofBeanDefinitionRegistryPostProcessor){//进行强制转化BeanDefinitionRegistryPostProcessorregistryProcessor=(BeanDefinitionRegistryPostProcessor)postProcessor;//调用他作为BeanDefinitionRegistryPostProcessor的处理器的后置方法registryProcessor.postProcessBeanDefinitionRegistry(registry);//添加到我们用于保存的BeanDefinitionRegistryPostProcessor的集合中registryProcessors.add(registryProcessor);}else{//若没有实现BeanDefinitionRegistryPostProcessor接口,那么他就是BeanFactoryPostProcessor//把当前的后置处理器加入到regularPostProcessors中regularPostProcessors.add(postProcessor);}}//定义一个集合用户保存当前准备创建的BeanDefinitionRegistryPostProcessorList<BeanDefinitionRegistryPostProcessor>currentRegistryProcessors=newArrayList<>();//第一步:去容器中获取BeanDefinitionRegistryPostProcessor的bean的处理器名称String[]postProcessorNames=beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class,true,false);//循环筛选出来的匹配BeanDefinitionRegistryPostProcessor的类型名称for(StringppName:postProcessorNames){//判断是否实现了PriorityOrdered接口的if(beanFactory.isTypeMatch(ppName,PriorityOrdered.class)){//显示的调用getBean()的方式获取出该对象然后加入到currentRegistryProcessors集合中去currentRegistryProcessors.add(beanFactory.getBean(ppName,BeanDefinitionRegistryPostProcessor.class));//同时也加入到processedBeans集合中去processedBeans.add(ppName);}}//对currentRegistryProcessors集合中BeanDefinitionRegistryPostProcessor进行排序sortPostProcessors(currentRegistryProcessors,beanFactory);//把当前的加入到总的里面去registryProcessors.addAll(currentRegistryProcessors);/***在这里典型的BeanDefinitionRegistryPostProcessor就是ConfigurationClassPostProcessor*用于进行bean定义的加载比如我们的包扫描,@import等等。。。。。。。。。*详细往下查看invokeBeanDefinitionRegistryPostProcessors方法源码*/invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors,registry);//调用完之后,马上clea掉currentRegistryProcessors.clear();//---------------------------------------调用内置实现PriorityOrdered接口ConfigurationClassPostProcessor完毕--优先级No1-End----------------------------------------------------------------------------------------------------------------------------//去容器中获取BeanDefinitionRegistryPostProcessor的bean的处理器名称(内置的和上面注册的)postProcessorNames=beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class,true,false);//循环上一步获取的BeanDefinitionRegistryPostProcessor的类型名称for(StringppName:postProcessorNames){//表示没有被处理过,且实现了Ordered接口的if(!processedBeans.contains(ppName)&&beanFactory.isTypeMatch(ppName,Ordered.class)){//显示的调用getBean()的方式获取出该对象然后加入到currentRegistryProcessors集合中去currentRegistryProcessors.add(beanFactory.getBean(ppName,BeanDefinitionRegistryPostProcessor.class));//同时也加入到processedBeans集合中去processedBeans.add(ppName);}}//对currentRegistryProcessors集合中BeanDefinitionRegistryPostProcessor进行排序sortPostProcessors(currentRegistryProcessors,beanFactory);//把他加入到用于保存到registryProcessors中registryProcessors.addAll(currentRegistryProcessors);//调用他的后置处理方法invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors,registry);//调用完之后,马上clea掉currentRegistryProcessors.clear();//-----------------------------------------调用自定义Order接口BeanDefinitionRegistryPostProcessor完毕-优先级No2-End-----------------------------------------------------------------------------------------------------------------------------//调用没有实现任何优先级接口的BeanDefinitionRegistryPostProcessor//定义一个重复处理的开关变量默认值为truebooleanreiterate=true;//第一次就可以进来while(reiterate){//进入循环马上把开关变量给改为falsereiterate=false;//去容器中获取BeanDefinitionRegistryPostProcessor的bean的处理器名称postProcessorNames=beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class,true,false);//循环上一步获取的BeanDefinitionRegistryPostProcessor的类型名称for(StringppName:postProcessorNames){//没有被处理过的if(!processedBeans.contains(ppName)){//显示的调用getBean()的方式获取出该对象然后加入到currentRegistryProcessors集合中去currentRegistryProcessors.add(beanFactory.getBean(ppName,BeanDefinitionRegistryPostProcessor.class));//同时也加入到processedBeans集合中去processedBeans.add(ppName);//再次设置为truereiterate=true;}}//对currentRegistryProcessors集合中BeanDefinitionRegistryPostProcessor进行排序sortPostProcessors(currentRegistryProcessors,beanFactory);//把他加入到用于保存到registryProcessors中registryProcessors.addAll(currentRegistryProcessors);//调用他的后置处理方法invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors,registry);//进行clearcurrentRegistryProcessors.clear();}//-----------------------------------------调用没有实现任何优先级接口自定义BeanDefinitionRegistryPostProcessor完毕--End-----------------------------------------------------------------------------------------------------------------------------//调用BeanDefinitionRegistryPostProcessor.postProcessBeanFactory方法//详情源码往下看invokeBeanFactoryPostProcessorsinvokeBeanFactoryPostProcessors(registryProcessors,beanFactory);//调用BeanFactoryPostProcessor自设的(没有)invokeBeanFactoryPostProcessors(regularPostProcessors,beanFactory);}else{//若当前的beanFactory没有实现了BeanDefinitionRegistry说明没有注册Bean定义的能力//那么就直接调用BeanDefinitionRegistryPostProcessor.postProcessBeanFactory方法invokeBeanFactoryPostProcessors(beanFactoryPostProcessors,beanFactory);}//-----------------------------------------所有BeanDefinitionRegistryPostProcessor调用完毕--End-----------------------------------------------------------------------------------------------------------------------------//-----------------------------------------处理BeanFactoryPostProcessor--Begin-----------------------------------------------------------------------------------------------------------------------------//获取容器中所有的BeanFactoryPostProcessorString[]postProcessorNames=beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class,true,false);//保存BeanFactoryPostProcessor类型实现了priorityOrderedList<BeanFactoryPostProcessor>priorityOrderedPostProcessors=newArrayList<>();//保存BeanFactoryPostProcessor类型实现了Ordered接口的List<String>orderedPostProcessorNames=newArrayList<>();//保存BeanFactoryPostProcessor没有实现任何优先级接口的List<String>nonOrderedPostProcessorNames=newArrayList<>();for(StringppName:postProcessorNames){//processedBeans包含的话,表示在上面处理BeanDefinitionRegistryPostProcessor的时候处理过了if(processedBeans.contains(ppName)){//skip-alreadyprocessedinfirstphaseabove}//判断是否实现了PriorityOrdered优先级最高elseif(beanFactory.isTypeMatch(ppName,PriorityOrdered.class)){priorityOrderedPostProcessors.add(beanFactory.getBean(ppName,BeanFactoryPostProcessor.class));}//判断是否实现了Ordered优先级其次elseif(beanFactory.isTypeMatch(ppName,Ordered.class)){orderedPostProcessorNames.add(ppName);}//没有实现任何的优先级接口的最后调用else{nonOrderedPostProcessorNames.add(ppName);}}//排序sortPostProcessors(priorityOrderedPostProcessors,beanFactory);//先调用BeanFactoryPostProcessor实现了PriorityOrdered接口的invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors,beanFactory);//再调用BeanFactoryPostProcessor实现了Ordered.List<BeanFactoryPostProcessor>orderedPostProcessors=newArrayList<>();for(StringpostProcessorName:orderedPostProcessorNames){orderedPostProcessors.add(beanFactory.getBean(postProcessorName,BeanFactoryPostProcessor.class));}sortPostProcessors(orderedPostProcessors,beanFactory);invokeBeanFactoryPostProcessors(orderedPostProcessors,beanFactory);//调用没有实现任何方法接口的List<BeanFactoryPostProcessor>nonOrderedPostProcessors=newArrayList<>();for(StringpostProcessorName:nonOrderedPostProcessorNames){nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName,BeanFactoryPostProcessor.class));}invokeBeanFactoryPostProcessors(nonOrderedPostProcessors,beanFactory);//-----------------------------------------处理BeanFactoryPostProcessor--End-----------------------------------------------------------------------------------------------------------------------------//Clearcachedmergedbeandefinitionssincethepost-processorsmighthave//modifiedtheoriginalmetadata,e.g.replacingplaceholdersinvalues...beanFactory.clearMetadataCache();//-------------------------BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor调用完毕--End-----------------------------------------------------------------------------------------------------------------------------}
这个方法分为两部分,第一部分先调用所有实现了BeanDefinitionRegistry接口的后置处理器,第二部分处理BeanFactoryPostProcessor后置处理器。 实现了BeanDefinitionRegistry接口的后置处理器,也有先后的调用顺序: 首先:调用内置实现PriorityOrdered接口ConfigurationClassPostProcessor; 其次:调用自定义Order接口BeanDefinitionRegistryPostProcessor; 接着:调用没有实现任何优先级接口自定义BeanDefinitionRegistryPostProcessor; 最后:调用BeanFactoryPostProcessor 自定义的后置处理器;
invokeBeanDefinitionRegistryPostProcessors
进入到ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry方法,前面说过ConfigurationClassPostProcessor也实现了BeanDefinitionRegistryPostProcessor的接口。
publicvoidprocessConfigBeanDefinitions(BeanDefinitionRegistryregistry){List<BeanDefinitionHolder>configCandidates=newArrayList<>();//获取IOC容器中目前所有bean定义的名称String[]candidateNames=registry.getBeanDefinitionNames();//循环我们的上一步获取的所有的bean定义信息for(StringbeanName:candidateNames){//通过bean的名称来获取我们的bean定义对象BeanDefinitionbeanDef=registry.getBeanDefinition(beanName);//判断是否有没有解析过if(ConfigurationClassUtils.isFullConfigurationClass(beanDef)||ConfigurationClassUtils.isLiteConfigurationClass(beanDef)){if(logger.isDebugEnabled()){logger.debug("Beandefinitionhasalreadybeenprocessedasaconfigurationclass:"+beanDef);}}//进行正在的解析判断是不是完全的配置类还是一个非正式的配置类elseif(ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef,this.metadataReaderFactory)){//满足添加就加入到候选的配置类集合中configCandidates.add(newBeanDefinitionHolder(beanDef,beanName));}}//若没有找到配置类直接返回if(configCandidates.isEmpty()){return;}//对我们的配置类进行Order排序configCandidates.sort((bd1,bd2)->{inti1=ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());inti2=ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());returnInteger.compare(i1,i2);});//创建我们通过@CompentScan导入进来的beanname的生成器//创建我们通过@Import导入进来的bean的名称SingletonBeanRegistrysbr=null;if(registryinstanceofSingletonBeanRegistry){sbr=(SingletonBeanRegistry)registry;if(!this.localBeanNameGeneratorSet){BeanNameGeneratorgenerator=(BeanNameGenerator)sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);if(generator!=null){//设置@CompentScan导入进来的bean的名称生成器(默认类首字母小写)也可以自己定义,一般不会this.componentScanBeanNameGenerator=generator;//设置@Import导入进来的bean的名称生成器(默认类首字母小写)也可以自己定义,一般不会this.importBeanNameGenerator=generator;}}}if(this.environment==null){this.environment=newStandardEnvironment();}//创建一个配置类解析器对象ConfigurationClassParserparser=newConfigurationClassParser(this.metadataReaderFactory,this.problemReporter,this.environment,this.resourceLoader,this.componentScanBeanNameGenerator,registry);//用于保存我们的配置类BeanDefinitionHolder放入上面筛选出来的配置类Set<BeanDefinitionHolder>candidates=newLinkedHashSet<>(configCandidates);//用于保存我们的已经解析的配置类,长度默认为解析出来默认的配置类的集合长度Set<ConfigurationClass>alreadyParsed=newHashSet<>(configCandidates.size());//dowhile会进行第一次解析do{//真正的解析我们的配置类//详细源码往下看parse方法parser.parse(candidates);parser.validate();//解析出来的配置类Set<ConfigurationClass>configClasses=newLinkedHashSet<>(parser.getConfigurationClasses());configClasses.removeAll(alreadyParsed);//Readthemodelandcreatebeandefinitionsbasedonitscontentif(this.reader==null){this.reader=newConfigurationClassBeanDefinitionReader(registry,this.sourceExtractor,this.resourceLoader,this.environment,this.importBeanNameGenerator,parser.getImportRegistry());}//此处才把@Bean的方法和@Import注册到BeanDefinitionMap中this.reader.loadBeanDefinitions(configClasses);//加入到已经解析的集合中alreadyParsed.addAll(configClasses);candidates.clear();//判断我们ioc容器中的是不是>候选原始的bean定义的个数if(registry.getBeanDefinitionCount()>candidateNames.length){//获取所有的bean定义String[]newCandidateNames=registry.getBeanDefinitionNames();//原始的老的候选的bean定义Set<String>oldCandidateNames=newHashSet<>(Arrays.asList(candidateNames));Set<String>alreadyParsedClasses=newHashSet<>();//赋值已经解析的for(ConfigurationClassconfigurationClass:alreadyParsed){alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());}for(StringcandidateName:newCandidateNames){//表示当前循环的还没有被解析过if(!oldCandidateNames.contains(candidateName)){BeanDefinitionbd=registry.getBeanDefinition(candidateName);//判断有没有被解析过if(ConfigurationClassUtils.checkConfigurationClassCandidate(bd,this.metadataReaderFactory)&&!alreadyParsedClasses.contains(bd.getBeanClassName())){candidates.add(newBeanDefinitionHolder(bd,candidateName));}}}candidateNames=newCandidateNames;}}//存在没有解析过的需要循环解析while(!candidates.isEmpty());//RegistertheImportRegistryasabeaninordertosupportImportAware@Configurationclassesif(sbr!=null&&!sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)){sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME,parser.getImportRegistry());}if(this.metadataReaderFactoryinstanceofCachingMetadataReaderFactory){//ClearcacheinexternallyprovidedMetadataReaderFactory;thisisano-op//forasharedcachesinceit'llbeclearedbytheApplicationContext.((CachingMetadataReaderFactory)this.metadataReaderFactory).clearCache();}}
ConfigurationClassParser的parse方法
好深~~ 现在才到了真正解析配置类。
doProcessConfigurationClass
这里只看一个解析@ComponentScan 注解的实现。
@NullableprotectedfinalSourceClassdoProcessConfigurationClass(ConfigurationClassconfigClass,SourceClasssourceClass)throwsIOException{//Recursivelyprocessanymember(nested)classesfirstprocessMemberClasses(configClass,sourceClass);//处理我们的@propertySource注解的for(AnnotationAttributespropertySource:AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(),PropertySources.class,org.springframework.context.annotation.PropertySource.class)){if(this.environmentinstanceofConfigurableEnvironment){processPropertySource(propertySource);}else{logger.warn("Ignoring@PropertySourceannotationon["+sourceClass.getMetadata().getClassName()+"].Reason:EnvironmentmustimplementConfigurableEnvironment");}}//解析我们的@ComponentScan注解//从我们的配置类上解析处ComponentScans的对象集合属性Set<AnnotationAttributes>componentScans=AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(),ComponentScans.class,ComponentScan.class);if(!componentScans.isEmpty()&&!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(),ConfigurationPhase.REGISTER_BEAN)){//循环解析我们解析出来的AnnotationAttributesfor(AnnotationAttributescomponentScan:componentScans){//把我们扫描出来的类变为bean定义的集合真正的解析//详细往下看componentScanParser.parse源码Set<BeanDefinitionHolder>scannedBeanDefinitions=this.componentScanParser.parse(componentScan,sourceClass.getMetadata().getClassName());//循环处理我们包扫描出来的bean定义for(BeanDefinitionHolderholder:scannedBeanDefinitions){BeanDefinitionbdCand=holder.getBeanDefinition().getOriginatingBeanDefinition();if(bdCand==null){bdCand=holder.getBeanDefinition();}//判断当前扫描出来的bean定义是不是一个配置类,若是的话直接进行递归解析if(ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand,this.metadataReaderFactory)){//递归解析因为@Component算是lite配置类parse(bdCand.getBeanClassName(),holder.getBeanName());}}}}//处理@ImportannotationsprocessImports(configClass,sourceClass,getImports(sourceClass),true);//处理@ImportResourceannotationsAnnotationAttributesimportResource=AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(),ImportResource.class);if(importResource!=null){String[]resources=importResource.getStringArray("locations");Class<?extendsBeanDefinitionReader>readerClass=importResource.getClass("reader");for(Stringresource:resources){StringresolvedResource=this.environment.resolveRequiredPlaceholders(resource);configClass.addImportedResource(resolvedResource,readerClass);}}//处理@Beanmethods获取到我们配置类中所有标注了@Bean的方法Set<MethodMetadata>beanMethods=retrieveBeanMethodMetadata(sourceClass);for(MethodMetadatamethodMetadata:beanMethods){configClass.addBeanMethod(newBeanMethod(methodMetadata,configClass));}//处理配置类接口默认方法的@BeanprocessInterfaces(configClass,sourceClass);//处理配置类的父类的,循环再解析if(sourceClass.getMetadata().hasSuperClass()){Stringsuperclass=sourceClass.getMetadata().getSuperClassName();if(superclass!=null&&!superclass.startsWith("java")&&!this.knownSuperclasses.containsKey(superclass)){this.knownSuperclasses.put(superclass,configClass);//Superclassfound,returnitsannotationmetadataandrecursereturnsourceClass.getSuperClass();}}//没有父类解析完成returnnull;}
componentScanParser.parse方法
publicSet<BeanDefinitionHolder>parse(AnnotationAttributescomponentScan,finalStringdeclaringClass){//这里的scanner是新创建的,与最前面开始的构造函数中初始化的scanner不是同一个。ClassPathBeanDefinitionScannerscanner=newClassPathBeanDefinitionScanner(this.registry,componentScan.getBoolean("useDefaultFilters"),this.environment,this.resourceLoader);//为我们的扫描器设置beanName的生成器对象Class<?extendsBeanNameGenerator>generatorClass=componentScan.getClass("nameGenerator");booleanuseInheritedGenerator=(BeanNameGenerator.class==generatorClass);scanner.setBeanNameGenerator(useInheritedGenerator?this.beanNameGenerator:BeanUtils.instantiateClass(generatorClass));/***解析@Scope的ProxyMode属性,该属性可以将Bean创建问jdk代理或cglib代理*/ScopedProxyModescopedProxyMode=componentScan.getEnum("scopedProxy");if(scopedProxyMode!=ScopedProxyMode.DEFAULT){scanner.setScopedProxyMode(scopedProxyMode);}else{Class<?extendsScopeMetadataResolver>resolverClass=componentScan.getClass("scopeResolver");scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));}scanner.setResourcePattern(componentScan.getString("resourcePattern"));//设置CompentScan对象的includeFilters包含的属性for(AnnotationAttributesfilter:componentScan.getAnnotationArray("includeFilters")){for(TypeFiltertypeFilter:typeFiltersFor(filter)){scanner.addIncludeFilter(typeFilter);}}//设置CompentScan对象的excludeFilters包含的属性for(AnnotationAttributesfilter:componentScan.getAnnotationArray("excludeFilters")){for(TypeFiltertypeFilter:typeFiltersFor(filter)){scanner.addExcludeFilter(typeFilter);}}/***是否懒加载,此懒加载为componentScan延迟加载所有类*/booleanlazyInit=componentScan.getBoolean("lazyInit");if(lazyInit){scanner.getBeanDefinitionDefaults().setLazyInit(true);}//包路径com.tuling.iocbeanlifecicleSet<String>basePackages=newLinkedHashSet<>();String[]basePackagesArray=componentScan.getStringArray("basePackages");for(Stringpkg:basePackagesArray){String[]tokenized=StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);Collections.addAll(basePackages,tokenized);}for(Class<?>clazz:componentScan.getClassArray("basePackageClasses")){basePackages.add(ClassUtils.getPackageName(clazz));}if(basePackages.isEmpty()){basePackages.add(ClassUtils.getPackageName(declaringClass));}scanner.addExcludeFilter(newAbstractTypeHierarchyTraversingFilter(false,false){@OverrideprotectedbooleanmatchClassName(StringclassName){returndeclaringClass.equals(className);}});//真正的进行扫描解析//往下看scanner.doScan源码returnscanner.doScan(StringUtils.toStringArray(basePackages));}
scanner.doScan
protectedSet<BeanDefinitionHolder>doScan(String...basePackages){Assert.notEmpty(basePackages,"Atleastonebasepackagemustbespecified");//创建bean定义的holder对象用于保存扫描后生成的bean定义对象Set<BeanDefinitionHolder>beanDefinitions=newLinkedHashSet<>();//循环我们的包路径集合//即@ComponentScan(basePackages={"com.xxx.xxx"})//和@ComponentScans()for(StringbasePackage:basePackages){//找到候选的Components//详细往下看findCandidateComponents方法源码Set<BeanDefinition>candidates=findCandidateComponents(basePackage);for(BeanDefinitioncandidate:candidates){ScopeMetadatascopeMetadata=this.scopeMetadataResolver.resolveScopeMetadata(candidate);candidate.setScope(scopeMetadata.getScopeName());//设置我们的beanNameStringbeanName=this.beanNameGenerator.generateBeanName(candidate,this.registry);//这是默认配置autowire-candidateif(candidateinstanceofAbstractBeanDefinition){postProcessBeanDefinition((AbstractBeanDefinition)candidate,beanName);}//获取@Lazy@DependsOn等注解的数据设置到BeanDefinition中if(candidateinstanceofAnnotatedBeanDefinition){AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition)candidate);}//把我们解析出来的组件bean定义注册到我们的IOC容器中(容器中没有才注册)if(checkCandidate(beanName,candidate)){BeanDefinitionHolderdefinitionHolder=newBeanDefinitionHolder(candidate,beanName);definitionHolder=AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata,definitionHolder,this.registry);beanDefinitions.add(definitionHolder);//注册到IOC容器中DefaultListableBeanFactory.registerBeanDefinition方法registerBeanDefinition(definitionHolder,this.registry);}}}returnbeanDefinitions;}
findCandidateComponents
privateSet<BeanDefinition>scanCandidateComponents(StringbasePackage){Set<BeanDefinition>candidates=newLinkedHashSet<>();try{//把我们的包路径转为资源路径cn/xxx/MainConfigStringpackageSearchPath=ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+resolveBasePackage(basePackage)+'/'+this.resourcePattern;//扫描指定包路径下面的所有.class文件Resource[]resources=getResourcePatternResolver().getResources(packageSearchPath);booleantraceEnabled=logger.isTraceEnabled();booleandebugEnabled=logger.isDebugEnabled();//需要我们的resources集合for(Resourceresource:resources){if(traceEnabled){logger.trace("Scanning"+resource);}//判断当的是不是可读的if(resource.isReadable()){try{MetadataReadermetadataReader=getMetadataReaderFactory().getMetadataReader(resource);//是不是候选的组件if(isCandidateComponent(metadataReader)){//包装成为一个ScannedGenericBeanDefinitionScannedGenericBeanDefinitionsbd=newScannedGenericBeanDefinition(metadataReader);//并且设置class资源sbd.setResource(resource);sbd.setSource(resource);//这里面会判断是不是接口、顶级类、抽象类等不会加入集合,排除掉//跟mybatis集成要重写这个方法if(isCandidateComponent(sbd)){if(debugEnabled){logger.debug("Identifiedcandidatecomponentclass:"+resource);}//加入到集合中candidates.add(sbd);}else{if(debugEnabled){logger.debug("Ignoredbecausenotaconcretetop-levelclass:"+resource);}}}else{if(traceEnabled){logger.trace("Ignoredbecausenotmatchinganyfilter:"+resource);}}}catch(Throwableex){thrownewBeanDefinitionStoreException("Failedtoreadcandidatecomponentclass:"+resource,ex);}}else{if(traceEnabled){logger.trace("Ignoredbecausenotreadable:"+resource);}}}}catch(IOExceptionex){thrownewBeanDefinitionStoreException("I/Ofailureduringclasspathscanning",ex);}//返回returncandidates;}
invokeBeanFactoryPostProcessors
会去for循环调用所有后置处理器,这里没有自定义的实现后置处理器,因此只有一个内置的后置处理器也就是ConfigurationClassPostProcessor后置处理器,主要用来解析配置类。进入到postProcessBeanFactory方法。
在enhanceConfigurationClasses方法中使用cglib对配置类进行代理,因为@Bean方法到时候要进行创建Bean实例。 插入个问题:这边为什么要使用动态代理?举个例子: 配置类加与不加@Configuration的区别。
@Configuration@ComponentScan(basePackages={"com.xxx.xxxx"})publicclassMainConfig{@Bean("car")publicCarcar(){Carcar=newCar();car.setName("xxxx");car.setTank(tank());//如果不去ioc容器中拿是不是每次都会创建新的//因此这边会使用动态代理来进行增强//都会先根据方法名getBean("car")returncar;}@BeanpublicTanktank(){returnnewTank();}}如果去掉@Configuration注解,会每次的创建一个新的tank对象。
接着看源码:
enhanceConfigurationClasses
publicvoidenhanceConfigurationClasses(ConfigurableListableBeanFactorybeanFactory){Map<String,AbstractBeanDefinition>configBeanDefs=newLinkedHashMap<>();for(StringbeanName:beanFactory.getBeanDefinitionNames()){BeanDefinitionbeanDef=beanFactory.getBeanDefinition(beanName);/*只有full版配置类才会创建cglib代理(只有加@Configuration会给类标记为full)虽然我们在指定配置的时候不标注@Configuration也行,所以加不加注解的区别就在这里那么加了@Configuration和不加有本质上有什么区别的?当在配置类中一个@Bean使用方法的方式引用另一个Bean如果不加注解就会重复加载Bean如果加了@Configuration则会在这里创建cglib代理,当调用@Bean方法时会先检测容器中是否存在*/if(ConfigurationClassUtils.isFullConfigurationClass(beanDef)){if(!(beanDefinstanceofAbstractBeanDefinition)){thrownewBeanDefinitionStoreException("Cannotenhance@Configurationbeandefinition'"+beanName+"'sinceitisnotstoredinanAbstractBeanDefinitionsubclass");}elseif(logger.isWarnEnabled()&&beanFactory.containsSingleton(beanName)){logger.warn("Cannotenhance@Configurationbeandefinition'"+beanName+"'sinceitssingletoninstancehasbeencreatedtooearly.Thetypicalcause"+"isanon-static@BeanmethodwithaBeanDefinitionRegistryPostProcessor"+"returntype:Considerdeclaringsuchmethodsas'static'.");}configBeanDefs.put(beanName,(AbstractBeanDefinition)beanDef);}}if(configBeanDefs.isEmpty()){//nothingtoenhance->returnimmediatelyreturn;}ConfigurationClassEnhancerenhancer=newConfigurationClassEnhancer();for(Map.Entry<String,AbstractBeanDefinition>entry:configBeanDefs.entrySet()){AbstractBeanDefinitionbeanDef=entry.getValue();//Ifa@Configurationclassgetsproxied,alwaysproxythetargetclassbeanDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE,Boolean.TRUE);try{//Setenhancedsubclassoftheuser-specifiedbeanclassClass<?>configClass=beanDef.resolveBeanClass(this.beanClassLoader);if(configClass!=null){Class<?>enhancedClass=enhancer.enhance(configClass,this.beanClassLoader);if(configClass!=enhancedClass){if(logger.isDebugEnabled()){logger.debug(String.format("Replacingbeandefinition'%s'existingclass'%s'with"+"enhancedclass'%s'",entry.getKey(),configClass.getName(),enhancedClass.getName()));}//重新修改Bean定义的Class,在创建Bean的实例时将会实例cglib的类beanDef.setBeanClass(enhancedClass);}}}catch(Throwableex){thrownewIllegalStateException("Cannotloadconfigurationclass:"+beanDef.getBeanClassName(),ex);}}}
插入:判断是否是full配置类。
publicstaticbooleancheckConfigurationClassCandidate(BeanDefinitionbeanDef,MetadataReaderFactorymetadataReaderFactory){StringclassName=beanDef.getBeanClassName();if(className==null||beanDef.getFactoryMethodName()!=null){returnfalse;}AnnotationMetadatametadata;if(beanDefinstanceofAnnotatedBeanDefinition&&className.equals(((AnnotatedBeanDefinition)beanDef).getMetadata().getClassName())){//Canreusethepre-parsedmetadatafromthegivenBeanDefinition...metadata=((AnnotatedBeanDefinition)beanDef).getMetadata();}elseif(beanDefinstanceofAbstractBeanDefinition&&((AbstractBeanDefinition)beanDef).hasBeanClass()){//CheckalreadyloadedClassifpresent...//sincewepossiblycan'tevenloadtheclassfileforthisClass.Class<?>beanClass=((AbstractBeanDefinition)beanDef).getBeanClass();metadata=newStandardAnnotationMetadata(beanClass,true);}else{try{MetadataReadermetadataReader=metadataReaderFactory.getMetadataReader(className);metadata=metadataReader.getAnnotationMetadata();}catch(IOExceptionex){if(logger.isDebugEnabled()){logger.debug("Couldnotfindclassfileforintrospectingconfigurationannotations:"+className,ex);}returnfalse;}}/***判断是不是真正的配置类就是判断当前的bean的class上有没有标注了@Configuration注解*/if(isFullConfigurationCandidate(metadata)){//设置了标记beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE,CONFIGURATION_CLASS_FULL);}//这里判断该配置类是一个非正式的配置类(ComponentComponentScanImportImportResource)elseif(isLiteConfigurationCandidate(metadata)){beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE,CONFIGURATION_CLASS_LITE);}else{returnfalse;}//解析配置类上是否标注了@Order注解Integerorder=getOrder(metadata);if(order!=null){beanDef.setAttribute(ORDER_ATTRIBUTE,order);}returntrue;}