结论
SpringBoot程序启动类上的@SpringBootApplication注解由@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan三个注解组成;@EnableAutoConfiguration注解使用@Import注解导入AutoConfigurationImportSelector类,该类使用SpringFactoriesLoader类加载classpath下META-INF/spring.factories文件中EnableAutoConfiguration属性定义的一系列自动装配类,结合@Conditional注解实现按需加载;这些自动装配类在SpringBoot程序启动时被ConfigurationClassPostProcessor(BeanFactoryPostProcessor类型)后置处理器解析,得到一系列的BeanDefination类装载到Spring容器中。
ApplicationContext和ConfigurationClassPostProcessor
ApplicationContext是Spring的基础容器,在SpringBoot中ApplicationContext是在SpringApplication.run(String... args)方法中创建的。
public ConfigurableApplicationContext run(String... args) {
long startTime = System.nanoTime();
DefaultBootstrapContext bootstrapContext = createBootstrapContext();
ConfigurableApplicationContext context = null;
//...
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
//创建ApplicationContext
context = createApplicationContext();
context.setApplicationStartup(this.applicationStartup);
prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
//...
}
catch (Throwable ex) {
handleRunFailure(context, ex, listeners);
throw new IllegalStateException(ex);
}
return context;
}
进入ceateApplicationContext()方法
public class SpringApplication {
//工厂类Factory,负责具体创建ApplicationContext
private ApplicationContextFactory applicationContextFactory = ApplicationContextFactory.DEFAULT;
//...
protected ConfigurableApplicationContext createApplicationContext() {
//ApplicationContextFactory.DEFAULT = new DefaultApplicationContextFactory();
return this.applicationContextFactory.create(this.webApplicationType);
}
}
进入DefaultApplicationContextFactory.create方法
class DefaultApplicationContextFactory implements ApplicationContextFactory {
@Override
public ConfigurableApplicationContext create(WebApplicationType webApplicationType) {
try {
/*从clasapath:META-INFO/spring.factories中获取候选的ApplicationContextFactory列表
*遍历ApplicationContextFactory,检测ApplicationContext类型是否与应用程序匹配
*/
return getFromSpringFactories(webApplicationType, ApplicationContextFactory::create,
AnnotationConfigApplicationContext::new);
}
catch (Exception ex) {
throw new IllegalStateException("Unable create a default ApplicationContext instance, "
+ "you may need a custom ApplicationContextFactory", ex);
}
}
private <T> T getFromSpringFactories(WebApplicationType webApplicationType,
BiFunction<ApplicationContextFactory, WebApplicationType, T> action, Supplier<T> defaultResult) {
//候选ApplicationContextFactory分为两种
//1.响应式spring-webflux AnnotationConfigReactiveWebServerApplicationContext.Factory
//2.传统servlet spring-web AnnotationConfigServletWebServerApplicationContext.Factory
for (ApplicationContextFactory candidate : SpringFactoriesLoader.loadFactories(ApplicationContextFactory.class,
getClass().getClassLoader())) {
T result = action.apply(candidate, webApplicationType);
if (result != null) {
return result;
}
}
return (defaultResult != null) ? defaultResult.get() : null;
}
}
对于传统Servlet类型Spring Boot程序,最终实例化的ApplicationContext是AnnotationConfigServletWebServerApplicationContext,其构造函数如下:
public class AnnotationConfigServletWebServerApplicationContext extends ServletWebServerApplicationContext
implements AnnotationConfigRegistry {
private final AnnotatedBeanDefinitionReader reader;
private final ClassPathBeanDefinitionScanner scanner;
//...
/**
* Create a new {@link AnnotationConfigServletWebServerApplicationContext} that needs
* to be populated through {@link #register} calls and then manually
* {@linkplain #refresh refreshed}.
*/
public AnnotationConfigServletWebServerApplicationContext() {
//基于注解的BeanDefinition读取器
this.reader = new AnnotatedBeanDefinitionReader(this);
//基于类路径扫描的BeanDefinition读取器
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
//...
}
AnnotatedBeanDefinitionReader的构造函数向ApplicationContext中注入BeanFactoryPostProcessor后置处理器ConfigurationClassPostProcessor
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
//注册ConfigurationClassPostProcessor后置处理器
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
进入AnnotationConfigUtils.registerAnnotationConfigProcessors
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
// internalConfigurationAnnotationProcessor,用于处理@Configuration
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
//....