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 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";

hutdownHook 本质就是一个线程对象,容器销毁的时候会触发其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启动完毕。


目录
相关文章
|
8月前
|
Java
springboot启动时执行
springboot启动时执行
41 0
|
14天前
|
XML Java 关系型数据库
Springboot启动时报错Property ‘mapperLocations‘ was not specified.
Springboot启动时报错Property ‘mapperLocations‘ was not specified.
18 2
|
2月前
|
Java 测试技术 数据库
SpringBoot启动时设置不加载数据库
SpringBoot启动时设置不加载数据库
83 0
|
2月前
|
存储 Java API
你了解SpringBoot启动时API相关信息是用什么数据结构存储的吗?(上篇)
你了解SpringBoot启动时API相关信息是用什么数据结构存储的吗?(上篇)
42 0
|
2月前
|
Java Linux Windows
windows解决SpringBoot启动时:APPLICATION FAILED TO START
windows解决SpringBoot启动时:APPLICATION FAILED TO START
56 0
|
7月前
|
Java 容器
SpringBoot启动时都做了哪些事(三)?
SpringBoot启动时都做了哪些事(三)?
41 0
|
7月前
|
监控 安全 Java
SpringBoot启动时都做了哪些事(二)?
SpringBoot启动时都做了哪些事(二)?
53 0
|
7月前
|
Java
SpringBoot启动时都做了哪些事(一)?
SpringBoot启动时都做了哪些事(一)?
31 0
|
9月前
|
Java
如何修改springboot项目启动时的默认图标?
如何修改springboot项目启动时的默认图标?
如何修改springboot项目启动时的默认图标?
|
8月前
|
缓存 Java 数据库
Springboot项目启动时加载数据库数据到内存
Springboot项目启动时加载数据库数据到内存