什么是自动配置

基于引入的Jar包,自动配置类会去加载对应的配置类,并完成相应的配置。为Springboot的“开箱即用”提供了基础支撑。

Configuration 类

  • 广义上是 @Component 直接或间接修饰的类
  • 狭义上是 @Configuration 修饰的类

简化启动流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void run(Class<?> primaryClass) {
// 创建IoC容器
ApplicationContext context = createApplicationContext();
// 加载主类(@SpringBootApplication)
loadSources(context,primaryClass);

// 处理配置类,自动配置的周期
processConfigurationClasses(context);

// 实例化单例的bean
instantiateSingletonBeans(context);
// 如果是Web服务
startWebServer(context);
}

加载配置类

递归处理@ComponentScan@Import注解

@ComponentScan

对制定的package进行扫描,默认是搜索 被注解的 @Component

若没有指定扫描的package,则默认是当前类所在的package

若使用此方法则需要开发人员写入扫描的package

@Import

可以以显式地从其他地方加载配置类,避免使用性能较差的 @ComponentScan

导入方式:

  • 普通导入:@Import(XXX.class)

    若使用此方法则需要开发人员写入具体的类名

  • 接口ImportSelector:@Import(XXXImportSelector.class)

    使用这个方法来实现自动配置最合适

  • 接口ImportBeanDefinitioinRegisterar:@Import(XXXImportBeanDefinitionRegistrar.class)

    是针对BeanDefinition的一个补充

@SpringBootApplication

1
2
3
4
5
6
7
8
9
10
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
})
public @interface SpringBootApplication {}
@SpringBootConfiguration
1
2
3
4
5
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {}
@EnableAutoConfiguration
1
2
3
4
5
6
7
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {}

可以看出被@SpringBootApplication注解的类,继承了@Configuration;会对启动类所在的包进行扫描,并加载对应的配置类;最终导入AutoConfigurationImportSelector类,并调用selectImports方法,返回需要导入的配置类。

如何实现 AUtoconfigurationImportSelector

利用SpringFactories机制,SpringFactories是一个类,里面存放了所有需要导入的配置类。存放在META-INF/spring.factories文件中selectImports方法中,会调用getCandidateConfigurations方法,返回需要导入的配置类。

  1. 通过SpringFactoriesLoader类,加载META-INF/spring.factories文件中的配置类。
  2. 通过getSpringFactoriesLoaderFactoryClass方法,获取在spring.factories文件中的配置类,筛选出以 EnableAutoConfiguration为key的配置类。
  3. 根据@Conditional过滤掉不符合条件的配置类。

【B站目前讲的最透彻的SpringBoot自动配置,大厂面试必备知识点#安员外很有码】