privatebooleanisComponent(Class<?> type) { // This has to be a bit of a guess. The only way to be sure that this type is // eligible is to make a bean definition out of it and try to instantiate it. if (MergedAnnotations.from(type, SearchStrategy.TYPE_HIERARCHY).isPresent(Component.class)) { returntrue; } // Nested anonymous classes are not eligible for registration, nor are groovy // closures return !type.getName().matches(".*\\$_.*closure.*") && !type.isAnonymousClass() && type.getConstructors() != null && type.getConstructors().length != 0; }
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor) if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(newLoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(newContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } }
// Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // Separate between BeanDefinitionRegistryPostProcessors that implement // PriorityOrdered, Ordered, and the rest. // 用于保存本次要执行的BeanDefinitionRegistryPostProcessor List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = newArrayList<>();
// 3.调用所有实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessor实现类 // 3.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的Bean的beanName // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered. String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// 5.最后, 调用所有剩下的BeanDefinitionRegistryPostProcessors //没实现排序接口的调用 // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear. booleanreiterate=true; while (reiterate) { //如果所以的BeanDefinitionRegistryPostProcessor都调用过了就退出循环 reiterate = false; //5.1 获取实现了BeanDefinitionRegistryPostProcessor接口的所有类的BeanDefinition对象的beanName postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); //遍历postProcessorNames for (String ppName : postProcessorNames) { // 5.2 跳过已经执行过的 //如果以上两次都没有调用过的BeanDefinitionRegistryPostProcessor走下面的判断 if (!processedBeans.contains(ppName)) { //因为需要进行调用所以先获取BeanDefinitionRegistryPostProcessor类型的实例并添加到currentRegistryProcessors currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); //将BeanDefinition对象的beanName添加到processedBeans processedBeans.add(ppName); //如果有调用的再次循环 // 5.3 如果有BeanDefinitionRegistryPostProcessor被执行, 则有可能会产生新的BeanDefinitionRegistryPostProcessor, // 因此这边将reiterate赋值为true, 代表需要再循环查找一次 reiterate = true; } } //完成排序工作 sortPostProcessors(currentRegistryProcessors, beanFactory); //添加到registryProcessors registryProcessors.addAll(currentRegistryProcessors); // 5.4 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); //再次清空currentRegistryProcessors currentRegistryProcessors.clear(); }
//如果registryProcessors不为空的话最后一次完成一次调用 // 6.调用所有BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法(BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProcessor) // Now, invoke the postProcessBeanFactory callback of all processors handled so far. invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); // 7.最后, 调用入参beanFactoryPostProcessors中的普通BeanFactoryPostProcessor的postProcessBeanFactory方法 invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); } else { // Invoke factory processors registered with the context instance. //完成BeanFactoryPostProcessor的调用 invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); }
// 到这里 , 入参beanFactoryPostProcessors和容器中的所有BeanDefinitionRegistryPostProcessor已经全部处理完毕, // 下面开始处理容器中的所有BeanFactoryPostProcessor // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // 8.找出所有实现BeanFactoryPostProcessor接口的类 //获取实现了BeanFactoryPostProcessor接口的类,获取beanDefinition的名称 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered, // Ordered, and the rest. // 用于存放实现了PriorityOrdered接口的BeanFactoryPostProcessor List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = newArrayList<>(); // 用于存放实现了Ordered接口的BeanFactoryPostProcessor的beanName List<String> orderedPostProcessorNames = newArrayList<>(); // 用于存放普通BeanFactoryPostProcessor的beanName List<String> nonOrderedPostProcessorNames = newArrayList<>(); // 8.1 遍历postProcessorNames, 将BeanFactoryPostProcessor按实现PriorityOrdered、实现Ordered接口、普通三种区分开 for (String ppName : postProcessorNames) { // 8.2 跳过已经执行过的,如果上面步骤已经调用过的BeanDefinition跳过 if (processedBeans.contains(ppName)) { // skip - already processed in first phase above } //实现了PriorityOrdered接口的 elseif (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { // 8.3 添加实现了PriorityOrdered接口的BeanFactoryPostProcessor //实例化BeanFactoryPostProcessor并添加到priorityOrderedPostProcessors priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } //实现了Ordered接口的 elseif (beanFactory.isTypeMatch(ppName, Ordered.class)) { // 8.4 添加实现了Ordered接口的BeanFactoryPostProcessor的beanName orderedPostProcessorNames.add(ppName); } else { // 8.5 添加剩下的普通BeanFactoryPostProcessor的beanName nonOrderedPostProcessorNames.add(ppName); } }
// Clear cached merged bean definitions since the post-processors might have // modified the original metadata, e.g. replacing placeholders in values... // 12.清除元数据缓存(mergedBeanDefinitions、allBeanNamesByType、singletonBeanNamesByType), // 因为后处理器可能已经修改了原始元数据,例如, 替换值中的占位符... beanFactory.clearMetadataCache(); }
//初始化完成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(); } }
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);
@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 //解析@ComponentScan注解,扫描注解将包含有@ComCponent注解的类包装成BeanDefinitionHolder返回 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 //遍历所有的BeanDefinitionHolder for (BeanDefinitionHolder holder : scannedBeanDefinitions) { //从BeanDefinitionHolder中获取BeanDefinition BeanDefinitionbdCand= holder.getBeanDefinition().getOriginatingBeanDefinition(); if (bdCand == null) { bdCand = holder.getBeanDefinition(); } //检查是保存@Configuration注解有的话重新调用parse方法解析循环调用 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; }
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { // SPI获取EnableAutoConfiguration为key的所有实现类 List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct."); return configurations; }