总体流程
- 创建SpringApplication
分段解析
创建SpringApplication
- 主要内容为初始化类加载器、设置资源类、设置web应用类型,设置主方法类,设置初始化类和设置监听器
- 默认初始化类加载器为null,使用默认类加载器;
- 默认资源类由构造器参数传入,为springBootApplication启动类
- web应用类型由classPath下的包来确定,按照优先级分别为REACTIVE,SERVLET和NONE;根据是否引包确定web应用类型;
- 默认主方法类通过当前堆栈的main方法找到
- 默认初始化类加载springFactories中ApplicationContextInitializer的实现类;
- 默认监听器加载springFactories中ApplicationListener的实现类;
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
this.webApplicationType = WebApplicationType.deduceFromClasspath();
this.bootstrapRegistryInitializers = new ArrayList<>(
getSpringFactoriesInstances(BootstrapRegistryInitializer.class));
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
关于SpringFactories:
1 SpringFactories是springboot自动装配jar包中类方法的机制
2 当自定义包需要被Springboot加载时,在factories文件中写入org.springframework.boot.autoconfigure.EnableAutoConfiguration = 'xxx',用,号分割
3 当应用springFactories机制引包时,如果需要qualifier注解配合注入的,需要引用全限定包名
*4 springFactories与每个插件的配置类进行配合,完成starter的功能。即springFactories中EnableAutoConfiguration指定插件配置类
*5 更多springFactories相关可以参考这边博客 https://www.jianshu.com/p/00e49c607fa1
关于web应用类型:
1 当不引入Spring Boot Starter Web和Spring Boot Starter WebFlux包时,springboot是单体应用,执行完主程序会直接退出
2 当引入WEBFLUX包且满足其它包限定条件时,应用类型为WebFlux的REACTIVE类型,更多信息可以参考博文https://zhuanlan.zhihu.com/p/143614001
3 当引入Spring Boot Starter Web依赖包时,应用类型为SERVLET,后续会启动TOMCAT容器