序
在这篇博客中,对于注解方式的启动流程进行了一些分析,最后了一个很重要的类ConfigurationClassPostProcessor,因为篇幅原因只做了一些比较简单的介绍,特此开一篇博客,好好分析一波ConfigurationClassPostProcessor了
主要源码流程
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
String[] candidateNames = registry.getBeanDefinitionNames();
//获取容器中的BeanDefinition,对他们进行遍历处理
for (String beanName : candidateNames) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
//判断下该类有没有被ConfigurationClassPostProcessor类处理过
if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
//这里去判断BeanDenition中是否含有@Configuration注解或者@Bean注解或者@Component,@ComponentScan
//@Import,@ImportResource这些注解,要是包含,就加入到候选处理的集合中
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);
});
// Detect any custom bean name generation strategy supplied through the enclosing application context
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();
}
// 委托模式,创建一个委托对象
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 {
//核心处理方法,在这里对@Configuration注解或者@Bean注解或者@Component,@ComponentScan
//@Import,@ImportResource这些注解进行处理的
parser.parse(candidates);
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());
}
//加载注册BeanDefinition,该方法及其重要,对import,importResource,bean注解的类注册加载到容器中
this.reader.loadBeanDefinitions(configClasses);
alreadyParsed.addAll(configClasses);
candidates.clear();
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
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();
}
}
ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)方法这个方法有以下作用
1.校验类是否有被处理的必要(是否有@Component和其子类注解,ComponentScan,Import,ImportResource等)
2.对类中有@Configuration的注解进行特殊标记,之后这个类的实例化会被spring代理
public static boolean checkConfigurationClassCandidate(
BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
//...省略
//在这里对Configuration这个注解进行了分析
Map<String, Object> config = metadata.getAnnotationAttributes(Configuration.class.getName());
//Configuration的proxyBeanMethods属性,默认是true
if (config != null && !Boolean.FALSE.equals(config.get("proxyBeanMethods"))) {
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
}
//如果不是Configuration注解,或者proxyBeanMethods设置成了false就会进入到该逻辑中
//isConfigurationCandidate()方法中,对于其他注解进行了设置
else if (config != null || isConfigurationCandidate(metadata)) {
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
}
else {
return false;
}
// It's a full or lite configuration candidate... Let's determine the order value, if any.
Integer order = getOrder(metadata);
if (order != null) {
beanDef.setAttribute(ORDER_ATTRIBUTE, order);
}
return true;
}
ConfigurationClassUtils的isConfigurationCandidate(metadata)方法
这个方法中对Component,ComponentScan,Import,ImportResource等注解进行了匹配
//静态代码块candidateIndicators中加入了Component,ComponentScan,Import,ImportResource这些类
static {
candidateIndicators.add(Component.class.getName());
candidateIndicators.add(ComponentScan.class.getName());
candidateIndicators.add(Import.class.getName());
candidateIndicators.add(ImportResource.class.getName());
}
public static boolean isConfigurationCandidate(AnnotationMetadata metadata) {
// Do not consider an interface or an annotation...
if (metadata.isInterface()) {
return false;
}
// 在此筛选类上注解与candidateIndicators中的进行匹配
for (String indicator : candidateIndicators) {
if (metadata.isAnnotated(indicator)) {
return true;
}
}
// Finally, let's look for @Bean methods...
try {
//如果都木得会在这里去看类中有没有@Bean标签,这就是springboot启动类中加@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);
}
return false;
}
}
ConfigurationClassParser的processConfigurationClass方法
1.过滤掉Conditionl注解的标签所添加进去的类,这些Condition类中matches方法可以过滤掉不用parse的类
2.在这里解析了类,把它的内部类也找了出来,存入到一个SourceClass对象中
3.对ConfigurationClass进行处理
protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
//对Conditionl进行筛选
if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
return;
}
ConfigurationClass existingClass = this.configurationClasses.get(configClass);
if (existingClass != null) {
if (configClass.isImported()) {
if (existingClass.isImported()) {
existingClass.mergeImportedBy(configClass);
}
return;
}
else {
this.configurationClasses.remove(configClass);
this.knownSuperclasses.values().removeIf(configClass::equals);
}
}
//在这里解析了类,把它的内部类也找了出来,存入到一个SourceClass对象中
SourceClass sourceClass = asSourceClass(configClass, filter);
do {
//实际解析ConfigurationClass
sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
}
while (sourceClass != null);
this.configurationClasses.put(configClass, configClass);
}
ConditionEvaluator的shouldSkip方法的思路
1.看下有没有Conditional注解,没有直接返回false
2.有的话看看Conditional中的vale,把value中的Class对象进行实例化
3.最后循环实例化的Conditiona类,调用其matches方法进行判断
public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
//本类和其父类是否有Conditional注解
if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
return false;
}
if (phase == null) {
if (metadata instanceof AnnotationMetadata &&
ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
}
return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
}
List<Condition> conditions = new ArrayList<>();
//对拥有注解的value中的类进行实例化
for (String[] conditionClasses : getConditionClasses(metadata)) {
for (String conditionClass : conditionClasses) {
Condition condition = getCondition(conditionClass, this.context.getClassLoader());
conditions.add(condition);
}
}
AnnotationAwareOrderComparator.sort(conditions);
//循环
for (Condition condition : conditions) {
ConfigurationPhase requiredPhase = null;
if (condition instanceof ConfigurationCondition) {
requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
}
//这里如果condition.matches方法返回了false则会返回true
if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {
return true;
}
}
//要是循环结束未返回则返回false,表示可向下执行
return false;
}
ConfigurationClassParser的doProcessConfigurationClass方法
这个方法是核心所在了,它做了很多重要的工作
1.processMemberClasses方法去溯源,看内部类里面是否有需要处理的注解
2.对PropertySources注解的分析
3.对ComponentScans注解的解析
4.对important注解进行解析
5.对importResource注解进行解析
6.对Bean注解进行解析
7.对接口的默认方法进行处理
@Nullable
protected final SourceClass doProcessConfigurationClass(
ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
throws IOException {
if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
//内部类里面是否有需要处理的注解
processMemberClasses(configClass, sourceClass, filter);
}
//@PropertySource 注解解析
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注解的解析
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();
}
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}
//@Import注解的解析
processImports(configClass, sourceClass, getImports(sourceClass), filter, true);
//@ImportResource 注解的解析
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注解的解析
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}
// 处理接口默认方法
processInterfaces(configClass, sourceClass);
// 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;
}
各个注解处理
ConfigurationClassParser的processMemberClasses方法这个方法是对内部类的一个处理,将内部类中符合条件的类解析出来,加入到BeanDefinition中,对于新加入的BeanDefinition也会调用processConfigurationClass方法,就这样递归下去,得到所有的内部类,当然只有@Component注解及其子注解会被再解析内部类,如果解析的内部类只是有其他注解,那么完成其他注解的任务即可
private void processMemberClasses(ConfigurationClass configClass, SourceClass sourceClass,
Predicate<String> filter) throws IOException {
//sourceClass在processConfigurationClass中已经处理好了,其中的内部类对象存储在其中
Collection<SourceClass> memberClasses = sourceClass.getMemberClasses();
if (!memberClasses.isEmpty()) {
List<SourceClass> candidates = new ArrayList<>(memberClasses.size());
for (SourceClass memberClass : memberClasses) {
//ConfigurationClassUtils.isConfigurationCandidate()方法正在前面分析过了.
//主要是对Component,ComponentScan,Import,ImportResource等注解进行了匹配
if (ConfigurationClassUtils.isConfigurationCandidate(memberClass.getMetadata()) &&
!memberClass.getMetadata().getClassName().equals(configClass.getMetadata().getClassName())) {
//加入候选再处理的集合中
candidates.add(memberClass);
}
}
//排序
OrderComparator.sort(candidates);
for (SourceClass candidate : candidates) {
if (this.importStack.contains(configClass)) {
this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
}
else {
this.importStack.push(configClass);
try {
//在这里又会对新加入的类调用processConfigurationClass方法去解析它里面的注解
processConfigurationClass(candidate.asConfigClass(configClass), filter);
}
finally {
this.importStack.pop();
}
}
}
}
}
processPropertySource是基于@PropertySource注解进行的一个解析方法,主要工作是把properties配置文件加载到容器的环境中
private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
//对注解信息进行解析
String name = propertySource.getString("name");
if (!StringUtils.hasLength(name)) {
name = null;
}
String encoding = propertySource.getString("encoding");
if (!StringUtils.hasLength(encoding)) {
encoding = null;
}
String[] locations = propertySource.getStringArray("value");
Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");
Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass));
for (String location : locations) {
try {
//解析出地址
String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
//把地址中的文件解析为resource对象
Resource resource = this.resourceLoader.getResource(resolvedLocation);
//加到Enviroment中
addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
}
//......
}
那么这些配置文件是何时被放入容器中的呢,在这篇中,放入容器是在最后的doProcessProperties()中实现的.
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
if (!beanFactory.hasEmbeddedValueResolver()) {
//在这里把解析的文件放入容器中
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
//......................
// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();
}
它解析的方法是**strVal -> getEnvironment().resolvePlaceholders(strVal)**这样子的.本质上与用xml标签解析的差别就是,注解使用的是本地的Enviroment去存储properties文件信息而xml标签解析是重新生产等了一个存储信息的类,并且这个类中有原本容器Enviroment这个对象.其实配置文件的注入最终还是要把解析好的信息放入 EmbeddedValueResolver 中的,这个在之后的Bean的依赖注入
@ComponentScans的注解解析是比较容易的,在之前这篇博客中,对于ClassPathBeanDefinitionScanner这个类有较为详细的分析和实践,在这里,实际上就是创建了一个ClassPathBeanDefinitionScanner去扫描包下的类,转为BeanDefinition,当然对新生的类也会经历老类一样的解析待遇,如此子子孙孙递归下去
//@ComponentScan注解的解析
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
//这里的shouldSkip在之前已经分析过了,是对@Conditional注解的处理,控制扫描的类
if (!componentScans.isEmpty() &&
!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
for (AnnotationAttributes componentScan : componentScans) {
// 这个里面实质上是new了一个ClassPathBeanDefinitionScanner去扫描
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
// 对扫描出来的新类进行遍历加入容器,并再此调用parse方法,递归完所有关联的@ComponentScans注解
for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
if (bdCand == null) {
bdCand = holder.getBeanDefinition();
}
//这里再次使用了checkConfigurationClassCandidate方法,类似于之前类被解析的步骤
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
//符合的再次被parse
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}
@import注解也是一个引入类的方式,但更加重要的作用是和springboot相关的,如果说到了springBoot的话,就又要说很多,在此不去深入,只在此做一些源码简单的分析
private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
Collection<SourceClass> importCandidates, Predicate<String> exclusionFilter,
boolean checkForCircularImports) {
if (importCandidates.isEmpty()) {
return;
}
//这里防止循环Import
if (checkForCircularImports && isChainedImportOnStack(configClass)) {
this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
}
else {
this.importStack.push(configClass);
try {
for (SourceClass candidate : importCandidates) {
//如果引入的类是ImportSelector的子类
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);
}
//这个部分,我暂时只清楚可能和SpringBoot解析有关,暂时不做分析
if (selector instanceof DeferredImportSelector) {
this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
}
else {
//获取ImportSelector的实现方法中需要加入的类
String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter);
//再来一次processImports(),对ImportSelector类中写的类统一引入
processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false);
}
}
//如果important的是ImportBeanDefinitionRegistrar类的话,也是跟SpringBoot相关的东西在此不深入
else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
// Candidate class is an ImportBeanDefinitionRegistrar ->
// delegate to it to register additional bean definitions
Class<?> candidateClass = candidate.loadClass();
ImportBeanDefinitionRegistrar registrar =
ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
this.environment, this.resourceLoader, this.registry);
configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
}
else {
// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
// process it as an @Configuration class
this.importStack.registerImport(
currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
//对Import注解引入的类进行 processConfigurationClass的递归解析
processConfigurationClass(candidate.asConfigClass(configClass), exclusionFilter);
}
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to process import candidates for configuration class [" +
configClass.getMetadata().getClassName() + "]", ex);
}
finally {
this.importStack.pop();
}
}
}
//@ImportResource 注解的解析
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);
//将文件位置信息加入到ImportedResource中
configClass.addImportedResource(resolvedResource, readerClass);
}
}
ConfigurationClassBeanDefinitionReader的loadBeanDefinitionsFromImportedResources方法这个方法在this.reader.loadBeanDefinitions(configClasses)中被调用到,是用来解析xml文件的,当然也是支持自定义的文件解析的.
这里主要看下xml文件的解析
private void loadBeanDefinitionsFromImportedResources(
Map<String, Class<? extends BeanDefinitionReader>> importedResources) {
Map<Class<?>, BeanDefinitionReader> readerInstanceCache = new HashMap<>();
importedResources.forEach((resource, readerClass) -> {
// Default reader selection necessary?
if (BeanDefinitionReader.class == readerClass) {
if (StringUtils.endsWithIgnoreCase(resource, ".groovy")) {
// When clearly asking for Groovy, that's what they'll get...
readerClass = GroovyBeanDefinitionReader.class;
}
else {
// 在这里定义xml的解析类
readerClass = XmlBeanDefinitionReader.class;
}
}
//这里看有没有自定义的解析类
BeanDefinitionReader reader = readerInstanceCache.get(readerClass);
if (reader == null) {
//.....
}
// xml文件的解析
reader.loadBeanDefinitions(resource);
});
}
**reader.loadBeanDefinitions(resource);**这一段是xml文件的解析了.可以看这篇博客.有详细的流程
ConfigurationClassBeanDefinitionReader的loadBeanDefinitionsForBeanMethod方法这个方法在this.reader.loadBeanDefinitions(configClasses)中被调用到,方法太长,不贴出来了,有兴趣可以自己看下
结
ConfigurationClassPostProcessor是很重要的一个类,其中对于spring的自动化配置,注解的解析功能完成的必备类,也是支持起springboot的关键.