publicclassConfigurationClassPostProcessorimplementsBeanDefinitionRegistryPostProcessor,PriorityOrdered,ResourceLoaderAware,BeanClassLoaderAware,EnvironmentAware{publicvoidprocessConfigBeanDefinitions(BeanDefinitionRegistryregistry){List<BeanDefinitionHolder>configCandidates=newArrayList<>();// 获取到所有的BeanDefinitionNamesString[]candidateNames=registry.getBeanDefinitionNames();// 循环调用for(StringbeanName:candidateNames){BeanDefinitionbeanDef=registry.getBeanDefinition(beanName);// 省略无关代码...//检查给定的bean定义是否适合配置类(或在配置/组件类中声明的嵌套组件类,也要自动注册),并进行相应标记。if(ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef,this.metadataReaderFactory)){configCandidates.add(newBeanDefinitionHolder(beanDef,beanName));}}// 省略无关代码...// Parse each @Configuration classConfigurationClassParserparser=newConfigurationClassParser(this.metadataReaderFactory,this.problemReporter,this.environment,this.resourceLoader,this.componentScanBeanNameGenerator,registry);Set<BeanDefinitionHolder>candidates=newLinkedHashSet<>(configCandidates);Set<ConfigurationClass>alreadyParsed=newHashSet<>(configCandidates.size());do{// TODO 重要程度:5 ConfigurationClassParser的parse方法调用,这里解析了一系列的注解parser.parse(candidates);parser.validate();Set<ConfigurationClass>configClasses=newLinkedHashSet<>(parser.getConfigurationClasses());configClasses.removeAll(alreadyParsed);// Read the model and create bean definitions based on its contentif(this.reader==null){this.reader=newConfigurationClassBeanDefinitionReader(registry,this.sourceExtractor,this.resourceLoader,this.environment,this.importBeanNameGenerator,parser.getImportRegistry());}// 这里装载了BeanDefinitionthis.reader.loadBeanDefinitions(configClasses);// 省略无关代码...}while(!candidates.isEmpty());// 省略无关代码...}}
classConfigurationClassParser{publicvoidparse(Set<BeanDefinitionHolder>configCandidates){for(BeanDefinitionHolderholder:configCandidates){BeanDefinitionbd=holder.getBeanDefinition();//这是哪个分支的解析会走到同一个方法里if(bdinstanceofAnnotatedBeanDefinition){//执行解析parse(((AnnotatedBeanDefinition)bd).getMetadata(),holder.getBeanName());}elseif(bdinstanceofAbstractBeanDefinition&&((AbstractBeanDefinition)bd).hasBeanClass()){//执行解析parse(((AbstractBeanDefinition)bd).getBeanClass(),holder.getBeanName());}else{// TODO 执行解析,记着这个方法,这里在满足条件时会被递归调用。parse(bd.getBeanClassName(),holder.getBeanName());}}this.deferredImportSelectorHandler.process();}}
classConfigurationClassParser{protectedvoidprocessConfigurationClass(ConfigurationClassconfigClass)throwsIOException{// 省略无关代码...// Recursively process the configuration class and its superclass hierarchy.SourceClasssourceClass=asSourceClass(configClass);do{// 执行解析sourceClass=doProcessConfigurationClass(configClass,sourceClass);}while(sourceClass!=null);// 这里将配置类的信息放入缓存中,等解析完之后,会将配置类进行LoadBeanDefinitions();this.configurationClasses.put(configClass,configClass);}}
classConfigurationClassParser{protectedfinalSourceClassdoProcessConfigurationClass(ConfigurationClassconfigClass,SourceClasssourceClass)throwsIOException{// Component注解支持if(configClass.getMetadata().isAnnotated(Component.class.getName())){// Recursively process any member (nested) classes firstprocessMemberClasses(configClass,sourceClass);}// Process any @PropertySource annotationsfor(AnnotationAttributespropertySource:AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(),PropertySources.class,org.springframework.context.annotation.PropertySource.class)){if(this.environmentinstanceofConfigurableEnvironment){processPropertySource(propertySource);}else{logger.info("Ignoring @PropertySource annotation on ["+sourceClass.getMetadata().getClassName()+"]. Reason: Environment must implement ConfigurableEnvironment");}}// @ComponentScan,@ComponentScans支持// Process any @ComponentScan annotationsSet<AnnotationAttributes>componentScans=AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(),ComponentScans.class,ComponentScan.class);if(!componentScans.isEmpty()&&!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(),ConfigurationPhase.REGISTER_BEAN)){for(AnnotationAttributescomponentScan:componentScans){// 使用@ComponentScan注释配置类->立即执行扫描// The config class is annotated with @ComponentScan -> perform the scan immediatelySet<BeanDefinitionHolder>scannedBeanDefinitions=this.componentScanParser.parse(componentScan,sourceClass.getMetadata().getClassName());// Check the set of scanned definitions for any further config classes and parse recursively if neededfor(BeanDefinitionHolderholder:scannedBeanDefinitions){BeanDefinitionbdCand=holder.getBeanDefinition().getOriginatingBeanDefinition();if(bdCand==null){bdCand=holder.getBeanDefinition();}// TODO 如果是配置类,则递归调用ConfigurationClassParser.parse()if(ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand,this.metadataReaderFactory)){parse(bdCand.getBeanClassName(),holder.getBeanName());}}}}// 处理@Import注解导入// Process any @Import annotationsprocessImports(configClass,sourceClass,getImports(sourceClass),true);// 处理@ImportResource注解导入// Process any @ImportResource annotationsAnnotationAttributesimportResource=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);}}// 处理@Bean注解的解析// Process individual @Bean methodsSet<MethodMetadata>beanMethods=retrieveBeanMethodMetadata(sourceClass);for(MethodMetadatamethodMetadata:beanMethods){configClass.addBeanMethod(newBeanMethod(methodMetadata,configClass));}// 处理接口上的默认方法// Process default methods on interfacesprocessInterfaces(configClass,sourceClass);// Process superclass, if anyif(sourceClass.getMetadata().hasSuperClass()){Stringsuperclass=sourceClass.getMetadata().getSuperClassName();if(superclass!=null&&!superclass.startsWith("java")&&!this.knownSuperclasses.containsKey(superclass)){this.knownSuperclasses.put(superclass,configClass);// Superclass found, return its annotation metadata and recursereturnsourceClass.getSuperClass();}}// No superclass -> processing is completereturnnull;}}
classConfigurationClassParser{privatevoidprocessImports(ConfigurationClassconfigClass,SourceClasscurrentSourceClass,Collection<SourceClass>importCandidates,booleancheckForCircularImports){if(importCandidates.isEmpty()){return;}// 检测循环导入if(checkForCircularImports&&isChainedImportOnStack(configClass)){this.problemReporter.error(newCircularImportProblem(configClass,this.importStack));}else{// 这里是一个ArrayDequethis.importStack.push(configClass);for(SourceClasscandidate:importCandidates){// 这里会处理ImportSelector类型的。if(candidate.isAssignable(ImportSelector.class)){// Candidate class is an ImportSelector -> delegate to it to determine importsClass<?>candidateClass=candidate.loadClass();ImportSelectorselector=BeanUtils.instantiateClass(candidateClass,ImportSelector.class);ParserStrategyUtils.invokeAwareMethods(selector,this.environment,this.resourceLoader,this.registry);if(selectorinstanceofDeferredImportSelector){this.deferredImportSelectorHandler.handle(configClass,(DeferredImportSelector)selector);}else{// 实例化 ImportSelector 后,会执行selectImports()方法。获取到一个className数组。// 将其封装为SourceClass,然后递归调用当前方法,最终会走到else语句块中。String[]importClassNames=selector.selectImports(currentSourceClass.getMetadata());Collection<SourceClass>importSourceClasses=asSourceClasses(importClassNames);processImports(configClass,currentSourceClass,importSourceClasses,false);}}// EnableAspectJAutoProxy中导入的AspectJAutoProxyRegistrar就是实现了ImportBeanDefinitionRegistrarelseif(candidate.isAssignable(ImportBeanDefinitionRegistrar.class)){// Candidate class is an ImportBeanDefinitionRegistrar ->// delegate to it to register additional bean definitionsClass<?>candidateClass=candidate.loadClass();ImportBeanDefinitionRegistrarregistrar=BeanUtils.instantiateClass(candidateClass,ImportBeanDefinitionRegistrar.class);ParserStrategyUtils.invokeAwareMethods(registrar,this.environment,this.resourceLoader,this.registry);configClass.addImportBeanDefinitionRegistrar(registrar,currentSourceClass.getMetadata());}else{// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->// process it as an @Configuration classthis.importStack.registerImport(currentSourceClass.getMetadata(),candidate.getMetadata().getClassName());processConfigurationClass(candidate.asConfigClass(configClass));}}}// 省略...}}