SpringBoot版本:2.1.1 ==》启动流程分析汇总
接上篇博客Spring Boot 2.1.1(十一)启动流程分析之设置系统属性spring.beaninfo.ignore、自定义banner图
目录
2.1、DefaultListableBeanFactory
3、AnnotationConfigServletWebServerApplicationContext
3.1、实例化AnnotatedBeanDefinitionReader
3.2、实例化ClassPathBeanDefinitionScanner
public ConfigurableApplicationContext run(String... args) {
....
try {
//本篇内容从本行开始记录
context = createApplicationContext();
//本篇内容记录到这,后续更新
....
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
}
流程分析
public static final String DEFAULT_SERVLET_WEB_CONTEXT_CLASS = "org.springframework.boot."
+ "web.servlet.context.AnnotationConfigServletWebServerApplicationContext";
public static final String DEFAULT_REACTIVE_WEB_CONTEXT_CLASS = "org.springframework."
+ "boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext";
public static final String DEFAULT_CONTEXT_CLASS = "org.springframework.context."
+ "annotation.AnnotationConfigApplicationContext";
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
//判断当前applicationContextClass是否为空,为空则根据web应用类型创建上下文
if (contextClass == null) {
try {
switch (this.webApplicationType) {
case SERVLET:
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
break;
case REACTIVE:
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
break;
default:
contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
}
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, "
+ "please specify an ApplicationContextClass",
ex);
}
}
//最终转换成是ConfigurableApplicationContext
return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
根据应用类型创建对应的ApplicationContext对象,这里最终创建的是AnnotationConfigServletWebServerApplicationContext。
要了解AnnotationConfigServletWebServerApplicationContext的实例化过程中都做了什么,先要了解其继承结构。下面是其类图。
会先从父类开始加载,追寻构造方法一直到AbstractApplicationContext。只在AbstractApplicationContext、GenericApplicationContext、以及AnnotationConfigServletWebServerApplicationContext中构造方法执行了操作。下面一个一个记录执行的操作。
1、AbstractApplicationContext
在AbstractApplicationContext中会做一些初始化,包括:
- 会得到Log对象
- 为上下文设置唯一id和显示名称
- 初始化BeanFactoryPostProcessors 的List集合
- 是否活跃标识active,1为true,0为false
- 是否已关闭标识closed,1为true,0为false
- 刷新和销毁的同步对象startupShutdownMonitor
- 初始化ApplicationListener<?>的Set集合
- 在构造方法中实例化一个ServletContextResourcePatternResolver,参数就是AnnotationConfigServletWebServerApplicationContext
在构造方法中调用的方法是子类GenericWebApplicationContext重写后的方法。 将AnnotationConfigServletWebServerApplicationContext作为一个resourceLoader传递到父类。
父类PathMatchingResourcePatternResolver是一个Ant模式通配符的Resource查找器,可以用来查找类路径下或者文件系统中的资源。在其中会实例化一个AntPathMatcher,该类实现Ant风格的路径模式。
解释一下BeanFactoryPostProcessors接口:
BeanFactoryPostProcessors:通过实现