springboot的完整启动流程
文章目录
eg:
书接 springboot初始化
上文讲述了具体的spring的初始化流程,接下来就是从run方法开始讲述完整的springboot2的启动流程,版本是2.6.4
计时
在将启动器,引导器,初始化器保存和确定了主类之后,返回最准确的可用系统计时器的当前值,以毫微秒为单位。
long startTime = System.nanoTime();
接着创建引导上下文(Context环境)
DefaultBootstrapContext bootstrapContext = createBootstrapContext();
进入createBootstrapContext()中查看源代码:
private DefaultBootstrapContext createBootstrapContext() {
DefaultBootstrapContext bootstrapContext = new DefaultBootstrapContext();
this.bootstrapRegistryInitializers.forEach((initializer) -> initializer.initialize(bootstrapContext));
return bootstrapContext;
}
-
首先创建DefaultBootstrapContext对象,保存信息。
-
接着获取之前所有的initializer并执行initialize(bootstrapContext)),来完成对引导启动器的环境设置
让当前应用进入headless模式
java.awt.headless
configureHeadlessProperty();
private void configureHeadlessProperty() {
System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS,
System.getProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless)));
}
获取所有运行监听器(为了方便所有Listener进行事件感知)
SpringApplicationRunListeners listeners = getRunListeners(args);
- 获取运行监听器的具体方法
- 源代码中依然是getSpringFactoriesInstances,从spring.factories中寻找SpringApplicationRunListener.class
private SpringApplicationRunListeners getRunListeners(String[] args) {
Class<?>[] types = new Class<?>[] {
SpringApplication.class, String[].class };
return new SpringApplicationRunListeners(logger,
getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args),
this.applicationStartup);
}
listeners.starting,遍历所有监听器,并且starting
doWithListeners中的foreach方法。
也相当于通知所有感兴趣(需要这个信息)系统正在启动的“人”,项目正在starting
void starting(ConfigurableBootstrapContext bootstrapContext, Class<?> mainApplicationClass) {
doWithListeners("spring.boot.application.starting", (listener) -> listener.starting(bootstrapContext),
(step) -> {
if (mainApplicationClas