http://www.javashuo.com/article/p-uvudtich-bm.htmlhtml
在上一篇文章中,咱们看到SpringApplication的静态方法最终是去构造了一个SpringApplication实例对象,并调用了SpringApplication的成员方法runspring
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) { return new SpringApplication(primarySources).run(args); }
本文将梳理一下run方法的代码主要的逻辑,为后面其它内容作一个铺垫app
跟进run方法,这个方法的代码有点长咱们将抛弃掉一些比较次要的内容spa
public ConfigurableApplicationContext run(String... args) { // 声明一个Context容器 ConfigurableApplicationContext context = null; // 获取监听器 SpringApplicationRunListeners listeners = getRunListeners(args); // 调用监听器的启动 listeners.starting(); try { // 建立并配置Environment(这个过程会加载application配置文件) ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); // 根据应用类型建立对应的Context容器 context = createApplicationContext(); // 刷新Context容器以前的准备 prepareContext(context, environment, listeners, applicationArguments, printedBanner); // 刷新Context容器 refreshContext(context); // 刷新Context容器以后处理 afterRefresh(context, applicationArguments); // Context容器refresh完毕发布 listeners.started(context); // 触发Context容器refresh完之后的执行 callRunners(context, applicationArguments); } catch (Throwable ex) {} try { // Context启动完毕,Runner运行完毕发布 listeners.running(context); } catch (Throwable ex) {} return context; }
简化后的代码看起来就比较清晰了,咱们再整理一下逻辑code
1)首先会从spring.factories配置文件中获取SpringApplicationRunListener监听器并启动监听器;htm
2)然后就会去建立Environment对象
3)紧接着建立ApplicationContextblog
4)ApplicationContext的refresh的事前准备事件
5)ApplicationContext的refreshget
6)ApplicationContext的refresh以后
7)发布ApplicationContext的refresh完毕的事件
8)触发runner
9)最后发布refresh完毕、runner执行完毕的事件
run方法描述了SpringApplication这个类的职责,包含了很多步骤,但简单的看其实就是为了建立并配置好一个ApplicationContext。
咱们忽略各类细节之后就会发现,SpringApplication的run方法主要就是为了构建出一个ApplicationContext,后续文章也将围绕着构建ApplicationContext相关的内容展开。