SpringBoot启动时都做了哪些事(四)?

关联博文:
SpringBoot启动时都做了哪些事(一)?
SpringBoot启动时都做了哪些事(二)?
SpringBoot启动时都做了哪些事(三)?
SpringBoot启动时都做了哪些事(四)?

SpringBoot启动时都做了哪些事(三)?后,我们继续分析SpringBoot启动过程流程。

本文我们分析应用上下文刷新以及后置处理。

回顾一下SpringApplication的run方法:

public ConfigurableApplicationContext run(String... args) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
		configureHeadlessProperty();
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting();
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
			ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
			configureIgnoreBeanInfo(environment);
			Banner printedBanner = printBanner(environment);
			context = createApplicationContext();
			exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
					new Class[] { ConfigurableApplicationContext.class }, context);
			prepareContext(context, environment, listeners, applicationArguments, printedBanner);
			refreshContext(context);
			afterRefresh(context, applicationArguments);
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
			}
			listeners.started(context);
			callRunners(context, applicationArguments);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, listeners);
			throw new IllegalStateException(ex);
		}

		try {
			listeners.running(context);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}

【1】refreshContext

① refresh

SpringApplication的refreshContext方法。

private void refreshContext(ConfigurableApplicationContext context) {
	refresh(context);
	if (this.registerShutdownHook) {
		try {
			context.registerShutdownHook();
		}
		catch (AccessControlException ex) {
			// Not allowed in some environments.
		}
	}
}

而refresh方法如下所示,最终会走到AbstractApplicationContext的refresh中。本文这里我们不再分析,详情可以参考系列博文:AbstractApplicationContext中refresh方法详解

protected void refresh(ApplicationContext applicationContext) {
	Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
	((AbstractApplicationContext) applicationContext).refresh();
}

// ServletWebServerApplicationContext
@Override
public final void refresh() throws BeansException, IllegalStateException {
	try {
	// 从这里就是实际AbstractApplicationContext的refresh方法,有12个核心流程
		super.refresh();
	}
	catch (RuntimeException ex) {
		stopAndReleaseWebServer();
		throw ex;
	}
}

② registerShutdownHook

注册销毁钩子,也就是当容器关闭的时候触发钩子的执行。如下所示,这里获取到一个shutdownHook,然后添加到了ApplicationShutdownHooks的IdentityHashMap<Thread, Thread> hooks;中。

// AbstractApplicationContext
@Override
public void registerShutdownHook() {
	if (this.shutdownHook == null) {
		// No shutdown hook registered yet.
		this.shutdownHook = new Thread(SHUTDOWN_HOOK_THREAD_NAME) {
			@Override
			public void run() {
				synchronized (startupShutdownMonitor) {
					doClose();
				}
			}
		};
		Runtime.getRuntime().addShutdownHook(this.shutdownHook);
	}
}

String SHUTDOWN_HOOK_THREAD_NAME = "SpringContextShutdownHook";

shutdownHook 本质就是一个线程对象,容器销毁的时候会触发其start执行。本文这里如上代码所示,会触发doClose方法。本文暂不展开分析,另起篇章进行研究。

【2】afterRefresh

如下所示,默认是个空方法。

// SpringApplication
protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) {
}

然后就是stopWatch的stop,意味着上下文已经创建并刷新完毕

stopWatch.stop();
if (this.logStartupInfo) {
	new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
// 日志打印,比如下面
Started RecommendApplication in 7470.961 seconds (JVM running for 7500.285)

【3】listener.started

SpringApplicationRunListeners的started方法,本质会触发EventPublishingRunListener的started方法。

void started(ConfigurableApplicationContext context) {
	for (SpringApplicationRunListener listener : this.listeners) {
		listener.started(context);
	}
}

最终如下所示,这里会广播ApplicationStartedEvent事件。

@Override
public void started(ConfigurableApplicationContext context) {
	context.publishEvent(new ApplicationStartedEvent(this.application, this.args, context));
}

如下所示,有三种监听器对该事件感兴趣。

RestartApplicationListener
BackgroundPreinitializer
DelegatingApplicationListener

【4】callRunners

SpringApplication的callRunners方法。如下所示,这里会扫描ApplicationRunner和CommandLineRunner,对其进行排序,然后遍历触发每一个实例的run方法。

private void callRunners(ApplicationContext context, ApplicationArguments args) {
	List<Object> runners = new ArrayList<>();
	runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
	runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
	AnnotationAwareOrderComparator.sort(runners);
	for (Object runner : new LinkedHashSet<>(runners)) {
		if (runner instanceof ApplicationRunner) {
			callRunner((ApplicationRunner) runner, args);
		}
		if (runner instanceof CommandLineRunner) {
			callRunner((CommandLineRunner) runner, args);
		}
	}
}

如下所示ApplicationRunner 与CommandLineRunner一样,都是功能性接口。自定义服务可以实现该接口,那么在应用启动完毕后会触发服务的run方法执行。

@FunctionalInterface
public interface ApplicationRunner {
	void run(ApplicationArguments args) throws Exception;
}

@FunctionalInterface
public interface CommandLineRunner {
	void run(String... args) throws Exception;
}

【5】listeners.running

SpringApplicationRunListeners的running方法,本质会触发EventPublishingRunListener的running方法。

void running(ConfigurableApplicationContext context) {
	for (SpringApplicationRunListener listener : this.listeners) {
		listener.running(context);
	}
}

最终会广播ApplicationReadyEvent事件。

@Override
public void running(ConfigurableApplicationContext context) {
	context.publishEvent(new ApplicationReadyEvent(this.application, this.args, context));
}

有如下五种监听器对ApplicationReadyEvent事件感兴趣。

0 = {RestartApplicationListener@4405} 
1 = {SpringApplicationAdminMXBeanRegistrar@11026} 
2 = {BackgroundPreinitializer@4410} 
3 = {DelegatingApplicationListener@4412} 
4 = {DelegatingApplicationListener@9414} 
5 = {ConditionEvaluationDeltaLoggingListener@11027} 

到此,SpringBoot启动完毕。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流烟默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值