SpringBoot 源码阅读(10):AutoConfigurationImportSelector(自动配置)

本文深入探讨了SpringBoot的AutoConfigurationImportSelector,它是@EnableAutoConfiguration注解背后的自动配置机制。从类的调用流程,到如何读取spring.factories文件,再到选择并处理配置类,以及条件注解的使用,揭示了SpringBoot自动配置的工作原理。
摘要由CSDN通过智能技术生成

AutoConfigurationImportSelector

public class AutoConfigurationImportSelector
		implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware,
		BeanFactoryAware, EnvironmentAware, Ordered {
   
		…………
}

该类为通过注解@EnableAutoConfiguration引入的类(见博客),用于自动配置。
首先看下该类在何处被调用(见博客):

if (candidate.isAssignable(ImportSelector.class)) {
   
	
	//加载class并实例化
	// Candidate class is an ImportSelector -> delegate to it to determine imports
	Class<?> candidateClass = candidate.loadClass();
	ImportSelector selector = BeanUtils.instantiateClass(candidateClass, ImportSelector.class);
	
	//注入相应的资源
	ParserStrategyUtils.invokeAwareMethods(
			selector, this.environment, this.resourceLoader, this.registry);
	
	//处理		
	if (selector instanceof DeferredImportSelector) {
   
		this.deferredImportSelectorHandler.handle(
				configClass, (DeferredImportSelector) selector);
	}
	else {
   
		String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
		Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames);
		processImports(configClass, currentSourceClass, importSourceClasses, false);
	}
}

AutoConfigurationImportSelector实现了DeferredImportSelector
核心就是:

public void handle(ConfigurationClass configClass, DeferredImportSelector importSelector) {
   

	DeferredImportSelectorHolder holder = new DeferredImportSelectorHolder(
			configClass, importSelector);
			
	if (this. Selectors == null) {
   
		DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
		handler.register(holder);
		handler.processGroupImports();
	}
	else {
   
		this.deferredImportSelectors.add(holder);
	}
}
@Nullable
private List<DeferredImportSelectorHolder> deferredImportSelectors = new ArrayList<>();

此时我们发现仅仅做了存储,defer是推迟的含义,那么在后面应该还有应用(调用其selectImports):
ConfigurationClassParser

public void parse(Set<BeanDefinitionHolder> configCandidates) {
   
	for (BeanDefinitionHolder holder : configCandidates) {
   
		BeanDefinition bd = holder.getBeanDefinition();
		try {
   
			if (bd instanceof AnnotatedBeanDefinition) {
   
				parse(((AnnotatedBeanDefinition) bd)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值