本章深入讲解 spring-boot 启动加载过程,以及spring加载启动中间件线程管理
通过 main 函数入口,两种方式启动主线程构建初始化spring
第一种通过SpringApplication.run方式:
ApplicationContext context = SpringApplication.run(Application.class, args);
第二种通过SpringApplicationBuilder方式:
ApplicationContext context = new SpringApplicationBuilder()
.sources(Application.class)
.run(args);
如果要用spring内置中间件,可以通过第二种方式利用context注册启动服务,如grpc服务:
// 参数
String[] args = {
};
registerAndStartGrpcServer(context, args);
通过springApplication构造方法
通过第二种分析:
new SpringApplicationBuilder() 做了什么,
①获取基于servlet的Web应用程序
②创建初始化器,通过META-INF/spring.factories 获取interface org.springframework.context.ApplicationContextInitializer的实现类实例,
③创建监听器同理,通过META-INF/spring.factories 获取interface org.springframework.context.ApplicationListener的实现类实例,
读取实现配置方法为loadFactoryNames()获取META-INF/spring.factories文件内容
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}
createSpringFactoriesInstances() 实例创建 和deduceMainApplicationClass() 都很好理解了。
.source() 仅仅将当前的入口类Application添加到sources,
.run(String… args) 将build()结果sources加入primarySources,
开始 run(String… args),分为两部分
#####第一步启动监听
① 创建监听器,通过META-INF/spring.factories 创建获取interface SpringApplicationRunListener实例,
其中实例EventPublishingRunListener构造时,创建SimpleApplicationEventMulticaster,用于启动各种内置的侦探监听,listeners如下
-interface ApplicationListener
|- RestartApplicationListener
|- BootstrapApplicationListener
|- LoggingApplicationListener
|- LiquibaseServiceLocatorApplicationListener
等,其中会区分确定给定侦听器是否支持给定的事件,然后通过ApplicationStartingEvent事件归类应用监听器retriever.applicationListeners
0 = {
RestartApplicationListener@3810}
1 = {
LoggingApplicationListener