一、invokeBeanFactoryPostProcessors 方法
invokeBeanFactoryPostProcessors
方法,调用各种后置处理器。
继承关系
BeanFactoryPostProcessors
BeanDefinitionRegistryPostProcessor
获得 BeanFactoryPostProcessors
invokeBeanFactoryPostProcessors 方法中先获得 BeanFactoryPostProcessors
注意:getBeanFactoryPostProcessors()
获得是自定义的 BeanFactoryPostProcessors,即:没有添加 @Component
注解的 BeanFactoryPostProcessors,手动交给 Spring 管理的。
1
| PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
|
1 2
| context.addBeanFactoryPostProcessor(new MyBeanDefinitionRegistryPostProcessor());
|
二、执行处理 BeanFactoryPostProcessor
1. 判断 beanFactory 是否为 BeanDefinitionRegistry 类型
当前 beanFactory
类型为 **DefaultListableBeanFactory
**。
如果是 BeanDefinitionRegistry
类型,则继续判断是否为 BeanDefinitionRegistryPostProcessor
子类型,并且循环优先处理 BeanDefinitionRegistryPostProcessor
类型。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) { if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) { BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor); } else { regularPostProcessors.add(postProcessor); } }
...... }
|
2. 处理 BeanDefinitionRegistryPostProcessor
ConfigurationClassPostProcessor # postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
方法。
1). 初始化 config bean 的容器集合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
String[] candidateNames = registry.getBeanDefinitionNames();
for (String beanName : candidateNames) { BeanDefinition beanDef = registry.getBeanDefinition(beanName); if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) { if (logger.isDebugEnabled()) { logger.debug("Bean definition has already been processed as a configuration class: " + beanDef); } } else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) { configCandidates.add(new BeanDefinitionHolder(beanDef, beanName)); } }
if (configCandidates.isEmpty()) { return; }
configCandidates.sort((bd1, bd2) -> { int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition()); int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition()); return Integer.compare(i1, i2); });
|
2). 生成 bean 的名称
也可以实现 BeanNameGenerator
接口,自定义 bean 的名称生成规则。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
SingletonBeanRegistry sbr = null; if (registry instanceof SingletonBeanRegistry) { sbr = (SingletonBeanRegistry) registry; if (!this.localBeanNameGeneratorSet) { BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton( AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR); if (generator != null) { this.componentScanBeanNameGenerator = generator; this.importBeanNameGenerator = generator; } } }
|
3). 封装为 ConfigurationClassParser
将当前 registry 后置处理器封装为 ConfigurationClassParser
。
1 2 3 4
| ConfigurationClassParser parser = new ConfigurationClassParser( this.metadataReaderFactory, this.problemReporter, this.environment, this.resourceLoader, this.componentScanBeanNameGenerator, registry);
|
4). 扫描包并解析配置类
找到普通 BeanDefinition 和 ConfigurationClass。
1 2 3 4 5 6 7 8 9 10 11 12 13
| Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates); Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size()); do { parser.parse(candidates); ...... this.reader.loadBeanDefinitions(configClasses); alreadyParsed.addAll(configClasses); ...... } while (!candidates.isEmpty());
|
doProcessConfigurationClass
方法中解析并处理 @ComponentScans
和 @ComponentScan
注解, @Imports
注解, @Bean
注解的方法。
调用链:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| org.springframework.context.annotation.ConfigurationClassParser#parse org.springframework.context.annotation.ConfigurationClassParser#processConfigurationClass org.springframework.context.annotation.ConfigurationClassParser#doProcessConfigurationClass
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable( sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class); if (!componentScans.isEmpty() && !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) { for (AnnotationAttributes componentScan : componentScans) { Set<BeanDefinitionHolder> scannedBeanDefinitions = this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName()); for (BeanDefinitionHolder holder : scannedBeanDefinitions) { BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition(); if (bdCand == null) { bdCand = holder.getBeanDefinition(); } if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) { parse(bdCand.getBeanClassName(), holder.getBeanName()); } } } }
processImports(configClass, sourceClass, getImports(sourceClass), filter, true);
......
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass); for (MethodMetadata methodMetadata : beanMethods) { configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass)); } ......
|
5). 处理 @Imports 注解,processImports 方法
处理 @Imports 注解,分别判断导入的类型:
- 普通类
- ImportSelector
- ImportBeanDefinitionRegistrar
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| if (checkForCircularImports && isChainedImportOnStack(configClass)) { this.problemReporter.error(new CircularImportProblem(configClass, this.importStack)); } else { this.importStack.push(configClass); try { for (SourceClass candidate : importCandidates) { if (candidate.isAssignable(ImportSelector.class)) { Class<?> candidateClass = candidate.loadClass(); ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class, this.environment, this.resourceLoader, this.registry); Predicate<String> selectorFilter = selector.getExclusionFilter(); if (selectorFilter != null) { exclusionFilter = exclusionFilter.or(selectorFilter); } if (selector instanceof DeferredImportSelector) { this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector); } else { String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata()); Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter); processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false); } } else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) { Class<?> candidateClass = candidate.loadClass(); ImportBeanDefinitionRegistrar registrar = ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class, this.environment, this.resourceLoader, this.registry); configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata()); } else { this.importStack.registerImport( currentSourceClass.getMetadata(), candidate.getMetadata().getClassName()); processConfigurationClass(candidate.asConfigClass(configClass), exclusionFilter); } } } catch () { ...... } }
|
3. invokeBeanFactoryPostProcessors 后续处理
解析完 PostProcessors 后,继续调用所有的 BeanDefinitionRegistryPostProcessor 实现,直到不再出现为止。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
|