SpringBoot运行源码分析:Spring应用上下文刷新

Spring应用上下文的刷新

Spring 应用上下文的刷新,是通过调用 SpringApplication 中的 refreshContext 方法来完成的。SpringApplication 中 refreshContext 方法相关代码如下。

private void refreshContext(ConfigurableApplicationContext context) {
//调用 refresh 方法
refresh(context);
if (this.registerShutdownHook) {
try
//注册 shutdownHook 线程, 实现销毁时的回调
context . registerShutdownHook();
} catch (AccessControlException ex) {
//在某些环境中不允许使用,会报出此异常,但此处并无处理操作
protected void refresh(ApplicationContext applicationContext) {
Assert. isInstanceOf(AbstractApplicationContext. class, applicationContex
t);
((AbstractAppl icationContext) applicat ionContext) .refresh();
}
}

其中 refresh 方法调用的是 AbstractApplicationContext 中的 refresh 方法,该类属于 spring-context 包。AbstractApplicationContext 的 refresh 方法更 多的是 Spring 相关的内容,这里我们通过 refresh 方法的顶层代码了解该方法都做了些什么,不过多深入 Spring 内部进行讲解。

blic void refresh() throws BeansException, IllegalStateException {
//整个过程同步处理
synchro