共计 12342 个字符,预计需要花费 31 分钟才能阅读完成。
spring 的 ConfigurationClassPostProcessor
次要是解析 @Configuration
类,通常只有一个入口类,对他进行递归解析,解析完所有关联类,包含应用 Configuration、Component、ComponentScan、Import、ImportResource、Bean
注解关联的类,将其注册进BeanFactory
中。
ConfigurationClassPostProcessor
类的结构图如下:
在创立容器SpringApplication#createApplicationContext
时将ConfigurationClassPostProcessor
注册进 ApplicationContext
中。
他实现了 BeanDefinitionRegistryPostProcessor
,将在 AbstractApplicationContext#refresh
中将在 BeanFactory
筹备好之后执行。
/**
* Derive further bean definitions from the configuration classes in the registry.
* 从派生类中注册更多的 bean
*/
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
// 生成 ID,如果蕴含则阐明该 BeanFactoryProcess 曾经执行过 postProcessBeanDefinitionRegistry 办法,不能反复解决
int registryId = System.identityHashCode(registry);
if (this.registriesPostProcessed.contains(registryId)) {
throw new IllegalStateException("postProcessBeanDefinitionRegistry already called on this post-processor against" + registry);
}
// 生成 ID,如果蕴含则阐明该 BeanFactoryProcess 曾经执行过 postProcessBeanFactory 办法,不能反复解决
if (this.factoriesPostProcessed.contains(registryId)) {
throw new IllegalStateException("postProcessBeanFactory already called on this post-processor against" + registry);
}
// 记录曾经执行过 postProcessBeanDefinitionRegistry 办法
this.registriesPostProcessed.add(registryId);
// 验证和注册 BeanDefinitions
processConfigBeanDefinitions(registry);
}
processConfigBeanDefinitions
逻辑次要是对配置类进行剖析,如果扫描到该配置类应用了Configuration、Component、ComponentScan、Import、ImportResource、Bean
注解,则认为是配置类。
- 在解析时,判断是否解析过,曾经被解析过不会再次解析,如果曾经解析过,会对其示意,依据
Configuration#proxyBeanMethods
的值进行标记:true 将其标识为full
,false 标识为lite
。 - 有须要进行解析的配置类,则会依据 order 进行排列解析程序。
- 应用
ConfigurationClassParser
对其进行解析,将解析到的配置类返回,应用ConfigurationClassBeanDefinitionReader
进行注册BeanDefinition
。 - 始终依照步骤 3 进行,直到解析完所有的配置类。
/**
* 1. 扫描入口类,在
*/
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
String[] candidateNames = registry.getBeanDefinitionNames();
// 查看 bean class 是否应用 Configuration、Component、ComponentScan、Import、ImportResource、Bean 注解。// 如果应用了,则将 beanDef 进行标识(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE)。for (String beanName : candidateNames) {BeanDefinition beanDef = registry.getBeanDefinition(beanName);
// beanDef 是否蕴含该属性,蕴含则阐明解决过
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));
}
}
// 没有配置类,则间接返回
// Return immediately if no @Configuration classes were found
if (configCandidates.isEmpty()) {return;}
// 依据 order 进行排序,从小到大,order 越小越前
// Sort by previously determined @Order value, if applicable
configCandidates.sort((bd1, bd2) -> {int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return Integer.compare(i1, i2);
});
// Detect any custom bean name generation strategy supplied through the enclosing application context
// 设置 bean 名称生成器
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;
}
}
}
if (this.environment == null) {this.environment = new StandardEnvironment();
}
// 解析配置类 (@configuration)
// Parse each @Configuration class
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
do {
// 解析
parser.parse(candidates);
// 验证:必须能够重写,不能是 final
parser.validate();
// 长期存储这次解析到的配置类
Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
// 移除曾经解析的配置类
configClasses.removeAll(alreadyParsed);
// Read the model and create bean definitions based on its content
// 创立解析器
if (this.reader == null) {
this.reader = new ConfigurationClassBeanDefinitionReader(
registry, this.sourceExtractor, this.resourceLoader, this.environment,
this.importBeanNameGenerator, parser.getImportRegistry());
}
// 向 BeanFactory 中注册 beanDefinition
this.reader.loadBeanDefinitions(configClasses);
// 增加曾经解析的类
alreadyParsed.addAll(configClasses);
// 解析完后清空
candidates.clear();
// 将本次解析进去的配置类存入 candidates 中,以供下一次循环进行解析。if (registry.getBeanDefinitionCount() > candidateNames.length) {String[] newCandidateNames = registry.getBeanDefinitionNames();
Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
Set<String> alreadyParsedClasses = new HashSet<>();
for (ConfigurationClass configurationClass : alreadyParsed) {alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
}
for (String candidateName : newCandidateNames) {if (!oldCandidateNames.contains(candidateName)) {BeanDefinition bd = registry.getBeanDefinition(candidateName);
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());
// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
// 增加 ImportRegistry
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();}
}
在整个解析过程中,ConfigurationClassParser
和 ConfigurationClassBeanDefinitionReader
起着关键作用。
ConfigurationClassParser
解析配置类,会将扫描到的 ConfigurationClass
返回,交由 ConfigurationClassBeanDefinitionReader
进行注册。
在 ConfigurationClassParser
解析过程中,如果碰到 @Component、@bean、@Import
等注解定义的类,将会委托给对应的处理器进行解决,这些类的解决形式与解决 @Configuration
注解定义的类不一样,在处理过程中就会将 BeanDefinition
注册进BeanFactory
。
ConfigurationClassParser#parse()
办法剖析
parse 办法外部调用的是 ConfigurationClassParser#processConfigurationClass
来进行解析
/**
* 传入须要解析的配置类
*/
public void parse(Set<BeanDefinitionHolder> configCandidates) {for (BeanDefinitionHolder holder : configCandidates) {BeanDefinition bd = holder.getBeanDefinition();
try {// 判断类型,各个分支最初都是调用 processConfigurationClass()
if (bd instanceof AnnotatedBeanDefinition) {parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
}
else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
}
else {parse(bd.getBeanClassName(), holder.getBeanName());
}
}
catch (BeanDefinitionStoreException ex) {throw ex;}
catch (Throwable ex) {
throw new BeanDefinitionStoreException("Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
}
}
// 导入应用 ImportSelector 注解 的配置类
this.deferredImportSelectorHandler.process();}
processConfigurationClass() 剖析
protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
// 是否跳过:解析 Conditional 条件
if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {return;}
ConfigurationClass existingClass = this.configurationClasses.get(configClass);
if (existingClass != null) {
// class 解析记录曾经存在,将其合并
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);
}
}
// 从以后类开始,递归向上通过 doProcessConfigurationClass 办法解决父类,直到是由 java 提供父类或曾经解决过为止。// Recursively process the configuration class and its superclass hierarchy.
SourceClass sourceClass = asSourceClass(configClass, filter);
do {sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
}
while (sourceClass != null);
// 记录该类曾经解决过。this.configurationClasses.put(configClass, configClass);
}
doProcessConfigurationClass
解决流程:
- 首先解决配置类的外部类
- 解决配置类上的
@PropertySource
注解 - 解决配置类上的
@ComponentScan
注解 - 解决配置类上的
@Import
注解 - 解决配置类上的
@ImportResource
注解 - 解决在配置类中应用到的
@Bean
的注解办法 - 解决配置类的接口默认办法
- 返回满足要求的父类,如果父类不须要解决或曾经解决过,返回 null,示意这个配置类曾经解决实现
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
throws IOException {
// @Configuration 组合了 @Component,所以应用了 @Configuration 会进入该办法,对内部类进行递归扫描
if (configClass.getMetadata().isAnnotated(Component.class.getName())) {// Recursively process any member (nested) classes first
processMemberClasses(configClass, sourceClass, filter);
}
// 解决 @PropertySource 注解,将 @PropertySource 指定的类创立并退出到 environment 中。// 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 注解,委托给 componentScanParser 解决
// 应用 ComponentScanAnnotationParser 扫描在配置类上应用到的 @ComponentScan 指定的包
// 将发现的类的 BeanDefinition 注册到 BeanFactory 中。// 之后在判断这些类是否是配置类,如果是,则对其进行递归扫描。// Process any @ComponentScan annotations
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) {
// 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) {BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
if (bdCand == null) {bdCand = holder.getBeanDefinition();
}
// 判断这些类是否是配置类,如果是,则对其进行递归扫描:执行 processConfigurationClass
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}
// 解决 @Import 注解
// 如果 @Import 指定的类实现了 ImportSelector 接口,应用 deferredImportSelectorHandler 进行解决
// 如果实现了 ImportBeanDefinitionRegistrar 接口,则将其记录到 importBeanDefinitionRegistrars 汇合中,在执行完该办法后进行解决。// 如果不是 ImportSelector 或 ImportBeanDefinitionRegistrar 的实现类,则对指定的类执行 processConfigurationClass 办法,进行解析。// Process any @Import annotations
processImports(configClass, sourceClass, getImports(sourceClass), filter, true);
// 解决 @ImportResource,将其记录到 importedResources 汇合中,供前面解决
// Process any @ImportResource annotations
AnnotationAttributes importResource =
AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
if (importResource != null) {String[] resources = importResource.getStringArray("locations");
Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
for (String resource : resources) {String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
configClass.addImportedResource(resolvedResource, readerClass);
}
}
// 解决配置类中应用 @Bean 的办法,找到所有用 @bean 注解的办法,保留进 beanMethods 中,供前面解决
// Process individual @Bean methods
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}
// 解决接口默认办法
// Process default methods on interfaces
processInterfaces(configClass, sourceClass);
// 解析超类,如果超类不是 java 结尾并且未解决过,返回 null
// Process superclass, if any
if (sourceClass.getMetadata().hasSuperClass()) {String superclass = 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
return null;
}