SpringBoot源码分析(三)

上篇我们讲解了监听器,以及初始化配置的文章,这章我们讲解下run方法

先看代码:

	public ConfigurableApplicationContext run(String... args) {
    // 初始化计时器
		StopWatch stopWatch = new StopWatch();
    // 开启计时器
		stopWatch.start();
    // 初始化配置为空
		ConfigurableApplicationContext context = null;
		// 声明一个异常集合
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    // 设置了一个名为java.awt.headless的系统属性,即使没有检测到显示器,也允许其启动.
		configureHeadlessProperty();
    // 创建所有 Spring 运行监听器并发布应用启动事件,我们上一章节演示的ApplicationListener就是他的本质
    // 我本章会演示这个方法,这个类一般不用,我们还是使用ApplicationListenner,SpringBoot本身也就是使用了一次,
		SpringApplicationRunListeners listeners = getRunListeners(args);
    // 执行这些SpringApplicationRunListener的starting()
		listeners.starting();
		try {
      // 解析args参数
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
      // 根据你的容器类型,加载一堆配置
			ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
			configureIgnoreBeanInfo(environment);
      // 输出一个图形的log,默认就是console
			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;
	}