springboot自动配置类

@SpringBootApplication的@EnableAutoConfiguration通过引入AutoConfigurationImportSelector开启了自动配置功能,AutoConfigurationImportSelector是DeferredImportSelector实现类,而DeferredImportSelector是通过DeferredImportSelectorHandler处理的。

DeferredImportSelector
DeferredImportSelector是延迟的,当解析到它时,先不执行它的导入方法,而是暂存起来,等到其他定义方式(@Bean,@Component,@ComponentScan)处理完在处理,使得Springboot的bean定义后于用户的bean定义加载,从而Springboot的bean上的条件注解(比如@ConditionalOnBean)能够根据用户的定义情况起作用。

//暂存
public void handle(ConfigurationClass configClass, DeferredImportSelector importSelector){
...
}
//处理
public void process() {
...
}

执行DeferredImportSelector.getImportGroup获取分组,如果分组不为空,执行org.springframework.context.annotation.DeferredImportSelector.Group#process和selectImports获取要定义的bean类;如果为空,执行DeferredImportSelector.selectImports获取

public interface DeferredImportSelector extends ImportSelector {
	@Nullable
	default Class<? extends Group> getImportGroup() {
		return null;
	}
	interface Group {
		void process(AnnotationMetadata metadata, DeferredImportSelector selector);
		Iterable<Entry> selectImports();
	}
}

AutoConfigurationImportSelector
它的getImportGroup()返回AutoConfigurationGroup

class AutoConfigurationGroup implements DeferredImportSelector.Group{
	public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) {
	...
	}
	public Iterable<Entry> selectImports() {
...
	}
}

process:

  1. 获取自动配置类名,从spring.factories读取名称为@EnableAutoConfiguration的值
  2. 获取要排除的类名,包括@EnableAutoConfiguration.exclude和excludeName、环境中的spring.autoconfigure.exclude,过滤
  3. 执行AutoConfigurationImportFilter.match对自动配置类进一步过滤,是更灵活的代码过滤。默认实现有OnBeanCondition、OnClassCondition和OnWebApplicationCondition,读取META-INF/spring-autoconfigure-metadata.properties,里面配置了使自动配置类生效的类,作为AutoConfigurationImportFilter的实现类时,只判断它们在类路径是否存在,不存在的过滤掉。作为SpringBootCondition实现类、加载Bean定义时,才会判断bean、类是否存在,是否为web应用的条件。通过这一步,实现了springboot引入jar包自动装配bean的功能

selectImports:

  • 对自动配置类进行排序,按照顺序进行ConfigurationClassParser#processImports解析,排序的目的是使ConditionOnXX能正常工作
  • 通过AutoConfigureOrder、AutoConfigureAfter和AutoConfigureBefore排序,一样则使用类名的字母顺序
  • AutoConfigureOrder、AutoConfigureAfter和AutoConfigureBefore的声明有2种方式,1、spring-autoconfigure-metadata.properties,2、注解
  • AutoConfigureAfter>当前类>AutoConfigureBefore

自动配置类

  • 自动配置类会当成@Import进来的类,也就是说会处理ImportSelector、ImportBeanDefinitionRegistrar和普通配置类的情况
  • 自动配置类如果加了@Configuration,相当于加了@Component的普通配置类,会解析它的内部类(java.lang.Class#getDeclaredClasses),包括所有可见性的静态内部类和内部类,作为配置类
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值