/** * 初始化完成BeanDefinition后调用该接口 进行已注册的BeanDefinition的增删改查 */ @Override publicvoidpostProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) { intregistryId= System.identityHashCode(registry); if (this.registriesPostProcessed.contains(registryId)) { thrownewIllegalStateException( "postProcessBeanDefinitionRegistry already called on this post-processor against " + registry); } if (this.factoriesPostProcessed.contains(registryId)) { thrownewIllegalStateException( "postProcessBeanFactory already called on this post-processor against " + registry); } this.registriesPostProcessed.add(registryId); //进行处理BeanDefinition processConfigBeanDefinitions(registry); }
// Read the model and create bean definitions based on its content if (this.reader == null) { this.reader = newConfigurationClassBeanDefinitionReader( registry, this.sourceExtractor, this.resourceLoader, this.environment, this.importBeanNameGenerator, parser.getImportRegistry()); } //设置BeanDefinition的属性值,重点看具体执行 @Import,@ImportSource,@Bean的逻辑 this.reader.loadBeanDefinitions(configClasses); //将注册完成的configClasses加入到alreadyParsed alreadyParsed.addAll(configClasses); //清除集合 candidates.clear(); if (registry.getBeanDefinitionCount() > candidateNames.length) { String[] newCandidateNames = registry.getBeanDefinitionNames(); Set<String> oldCandidateNames = newHashSet<>(Arrays.asList(candidateNames)); Set<String> alreadyParsedClasses = newHashSet<>(); for (ConfigurationClass configurationClass : alreadyParsed) { alreadyParsedClasses.add(configurationClass.getMetadata().getClassName()); } for (String candidateName : 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());
// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) { sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry()); }
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) { // Clear cache in externally provided MetadataReaderFactory; this is a no-op // for a shared cache since it'll be cleared by the ApplicationContext. ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache(); } }
/** * 检查metadata是否有一下注解@Component,@ComponentScan,@Import,@ImportResource,@Bean */ publicstaticbooleanisConfigurationCandidate(AnnotationMetadata metadata) { // Do not consider an interface or an annotation... if (metadata.isInterface()) { returnfalse; }
// Any of the typical annotations found? //检查metadata是否有@Component,@ComponentScan,@Import,@ImportResource中的一个 //有的话就返回true for (String indicator : candidateIndicators) { if (metadata.isAnnotated(indicator)) { returntrue; } }
// Finally, let's look for @Bean methods... try { //检查是方法中是否有@Bean的注解 return metadata.hasAnnotatedMethods(Bean.class.getName()); } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to introspect @Bean methods on class [" + metadata.getClassName() + "]: " + ex); } returnfalse; } }
protectedfinalvoidparse(@Nullable String className, String beanName)throws IOException { Assert.notNull(className, "No bean class name for configuration class bean definition"); MetadataReaderreader=this.metadataReaderFactory.getMetadataReader(className); processConfigurationClass(newConfigurationClass(reader, beanName)); }
/** * 解析ConfigurationClass */ protectedvoidprocessConfigurationClass(ConfigurationClass configClass)throws IOException { if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) { return; } //检查configurationClasses是否已经存在 ConfigurationClassexistingClass=this.configurationClasses.get(configClass); if (existingClass != null) { if (configClass.isImported()) { if (existingClass.isImported()) { existingClass.mergeImportedBy(configClass); } // Otherwise ignore new imported config class; existing non-imported class overrides it. return; } else { // Explicit bean definition found, probably replacing an import. // Let's remove the old one and go with the new one. this.configurationClasses.remove(configClass); this.knownSuperclasses.values().removeIf(configClass::equals); } }
// Recursively process the configuration class and its superclass hierarchy. //再次将configClass封装为SourceClass SourceClasssourceClass= asSourceClass(configClass); do { //解析ConfigurationClass sourceClass = doProcessConfigurationClass(configClass, sourceClass); } while (sourceClass != null);
/** * multiple times as relevant sources are discovered. * 解析ConfigurationClass * */ @Nullable protectedfinal SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass) throws IOException { //检查是否包含@Component注解 if (configClass.getMetadata().isAnnotated(Component.class.getName())) { // Recursively process any member (nested) classes first //处理@Component注解 processMemberClasses(configClass, sourceClass); }
// Process any @PropertySource annotations for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable( sourceClass.getMetadata(), PropertySources.class, org.springframework.context.annotation.PropertySource.class)) { if (this.environment instanceof ConfigurableEnvironment) { processPropertySource(propertySource); } else { logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() + "]. Reason: Environment must implement ConfigurableEnvironment"); } }
//对@ComponentScan注解的支撑 // Process any @ComponentScan annotations //搜集@ComponentScan注解 Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable( sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class); //搜集的@componentScans不为空 if (!componentScans.isEmpty() && !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) { //遍历所有包含@ComponentScan注解的类 for (AnnotationAttributes componentScan : componentScans) { // The config class is annotated with @ComponentScan -> perform the scan immediately Set<BeanDefinitionHolder> scannedBeanDefinitions = this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName()); // Check the set of scanned definitions for any further config classes and parse recursively if needed for (BeanDefinitionHolder holder : scannedBeanDefinitions) { BeanDefinitionbdCand= holder.getBeanDefinition().getOriginatingBeanDefinition(); if (bdCand == null) { bdCand = holder.getBeanDefinition(); } if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) { //解析@ComponentScan,对@ComponentScan注解的支撑 parse(bdCand.getBeanClassName(), holder.getBeanName()); } } } }
// Process any @Import annotations //对@Import注解的支撑 processImports(configClass, sourceClass, getImports(sourceClass), true);
// Process any @ImportResource annotations AnnotationAttributesimportResource= AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class); if (importResource != null) { String[] resources = importResource.getStringArray("locations"); Class<? extendsBeanDefinitionReader> readerClass = importResource.getClass("reader"); for (String resource : resources) { StringresolvedResource=this.environment.resolveRequiredPlaceholders(resource); configClass.addImportedResource(resolvedResource, readerClass); } }
// Process individual @Bean methods Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass); for (MethodMetadata methodMetadata : beanMethods) { configClass.addBeanMethod(newBeanMethod(methodMetadata, configClass)); }
// Process default methods on interfaces processInterfaces(configClass, sourceClass);
// Process superclass, if any if (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 recurse return sourceClass.getSuperClass(); } }
// No superclass -> processing is complete returnnull; }
// Do we need to mark the bean as skipped by its condition? if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) { configClass.skippedBeanMethods.add(methodName); return; } if (configClass.skippedBeanMethods.contains(methodName)) { return; } //获取@Bean的注解的bean AnnotationAttributesbean= AnnotationConfigUtils.attributesFor(metadata, Bean.class); Assert.state(bean != null, "No @Bean annotation attributes");
// Consider name and any aliases //获取name的属性 List<String> names = newArrayList<>(Arrays.asList(bean.getStringArray("name"))); StringbeanName= (!names.isEmpty() ? names.remove(0) : methodName);
// Register aliases even when overridden //注册别名 for (String alias : names) { this.registry.registerAlias(beanName, alias); }
// Has this effectively been overridden before (e.g. via XML)? //bean是否已经注册 if (isOverriddenByExistingDefinition(beanMethod, beanName)) { if (beanName.equals(beanMethod.getConfigurationClass().getBeanName())) { thrownewBeanDefinitionStoreException(beanMethod.getConfigurationClass().getResource().getDescription(), beanName, "Bean name derived from @Bean method '" + beanMethod.getMetadata().getMethodName() + "' clashes with bean name for containing configuration class; please make those names unique!"); } return; } //创建BeanDefinition ConfigurationClassBeanDefinitionbeanDef=newConfigurationClassBeanDefinition(configClass, metadata); //设置Resource beanDef.setResource(configClass.getResource()); //设置Source beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource())); //如果该类是静态的 if (metadata.isStatic()) { // static @Bean method //设置@bean的class if (configClass.getMetadata() instanceof StandardAnnotationMetadata) { //设置bean的class beanDef.setBeanClass(((StandardAnnotationMetadata) configClass.getMetadata()).getIntrospectedClass()); } else { //设置bean的className beanDef.setBeanClassName(configClass.getMetadata().getClassName()); } //设置唯一的bean的FactoryMethodName beanDef.setUniqueFactoryMethodName(methodName); } else { // instance @Bean method //不是静态的就设置工厂bean的name beanDef.setFactoryBeanName(configClass.getBeanName()); //设置唯一的bean的FactoryMethodName beanDef.setUniqueFactoryMethodName(methodName); }
/** * 对@ImportedResource的支持 */ privatevoidloadBeanDefinitionsFromImportedResources( Map<String, Class<? extends BeanDefinitionReader>> importedResources) { //创建read实例化的缓存 Map<Class<?>, BeanDefinitionReader> readerInstanceCache = newHashMap<>(); //遍历importedResources创建对应的解析器 importedResources.forEach((resource, readerClass) -> { // Default reader selection necessary? if (BeanDefinitionReader.class == readerClass) { //如果是groovy的文件 if (StringUtils.endsWithIgnoreCase(resource, ".groovy")) { // When clearly asking for Groovy, that's what they'll get... readerClass = GroovyBeanDefinitionReader.class; } else { //否则就是xml // Primarily ".xml" files but for any other extension as well readerClass = XmlBeanDefinitionReader.class; } } //从缓存中获取实例化的解析器 BeanDefinitionReaderreader= readerInstanceCache.get(readerClass); if (reader == null) { try { // Instantiate the specified BeanDefinitionReader //实例化解析器 reader = readerClass.getConstructor(BeanDefinitionRegistry.class).newInstance(this.registry); // Delegate the current ResourceLoader to it if possible //如果实现了AbstractBeanDefinitionReader接口 if (reader instanceof AbstractBeanDefinitionReader) { AbstractBeanDefinitionReaderabdr= ((AbstractBeanDefinitionReader) reader); abdr.setResourceLoader(this.resourceLoader); abdr.setEnvironment(this.environment); } //将实例化后的解析器加入缓存 readerInstanceCache.put(readerClass, reader); } catch (Throwable ex) { thrownewIllegalStateException( "Could not instantiate BeanDefinitionReader class [" + readerClass.getName() + "]"); } }
// TODO SPR-6310: qualify relative path locations as done in AbstractContextLoader.modifyLocations //进行加载资源 reader.loadBeanDefinitions(resource); }); }