上一章我们看到了SB的SpringApplication.java里面关于run Application的代码,其实前几章讲的都是些基本的入口代码,并没有到真正执行的代码,今天咱们就继续跟踪
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) { return run(new Class<?>[] { primarySource }, args); }
经过2次跳转后(忽略过跳转过程),到真正的run代码处:
/** * Run the Spring application, creating and refreshing a new * {@link ApplicationContext}. * @param args the application arguments (usually passed from a Java main method) * @return a running {@link ApplicationContext} */ public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch();//创建并开启一个停止监视器 stopWatch.start(); ConfigurableApplicationContext context = null; Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();//创建一个异常管理报告队列 configureHeadlessProperty();//配置程序,使之在没有显示器硬件/监视器情况下可以正常运行 SpringApplicationRunListeners listeners = getRunListeners(args);//创建并开启一个在SB框架运行期间的生命周期监听器,监听各类事件 listeners.starting(); try { ApplicationArguments applicationArguments = new DefaultApplicationArguments( args);//创建并初始化参数处理类 ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);//创建并处理环境变量 configureIgnoreBeanInfo(environment);//加载bean信息 Banner printedBanner = printBanner(environment);//创建并打印字符格式的banner 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;//返回上下文到run里 }