盒子
盒子

SpringBoot自动配置实现原理

SpringBoot能够实现自动配置主要依靠@SpringBootApplication

1
2
3
4
5
6
7
@SpringBootApplication
public class SecKillApplication {

public static void main(String[] args) {
SpringApplication.run(SecKillApplication.class, args);
}
}

@SpringBootApplication主要包括三个注解: @SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan注解,SpringBoot2.2.0后新增了第四个注解
ConfigurationPropertiesScan (申通面试题)

1

其中@EnableAutoConfiguration开启了自动配置,源码如下:

2

@AutoConfigurationPackage中导入了AutoConfigurationPackages.Registrar类,它的主要作用是将主配置类所在包及子包中包含的组件注册
AutoConfigurationImportSelector.class自动配置选择器,选择哪些类进行自动配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware,
ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {

// 自动配置主入口
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return NO_IMPORTS;
}
...
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(autoConfigurationMetadata,
annotationMetadata);
...
}

protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
AnnotationMetadata annotationMetadata) {
...
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
...
}

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
getBeanClassLoader());
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
}
}

自动配置类加载工厂,加载位于META-INF/spring.factories的类

1
2
3
public final class SpringFactoriesLoader {
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
...

3

4

总结:
在@SpringBootApplication中使用了@EnableAutoConfiguration开启了自动配置,其通过导入AutoConfigurationImportSelector自动配置选择器,选择哪些类进行自动配置,选择器借助于SpringFactoriesLoader自动配置类加载工厂加载META-INF/spring.factories,通过反射最终实例化对象,进而实现自动配置

支持一下
扫一扫,支持沈健
  • 微信扫一扫
  • 支付宝扫一扫