springboot启动解析二

此篇文章开始解析SpringApplication的run方法具体代码如下:

public ConfigurableApplicationContext run(String... args) {
        1.StopWatch stopWatch = new StopWatch();
        2.stopWatch.start();
        3.ConfigurableApplicationContext context = null;
        4.Collection exceptionReporters = new ArrayList<>();
        5.configureHeadlessProperty();
        6.SpringApplicationRunListeners listeners = getRunListeners(args);
        7.listeners.starting();
        try {
        8.  ApplicationArguments applicationArguments = new DefaultApplicationArguments(
                    args);
        9.  ConfigurableEnvironment environment = prepareEnvironment(listeners,
                    applicationArguments);
        10. configureIgnoreBeanInfo(environment);
        11. Banner printedBanner = printBanner(environment);
        12. context = createApplicationContext();
        13. exceptionReporters = getSpringFactoriesInstances(
                SpringBootExceptionReporter.class,
                    new Class[] { ConfigurableApplicationContext.class }, context);
        14.     prepareContext(context, environment, listeners, applicationArguments,
                    printedBanner);
        15. refreshContext(context);
        16. afterRefresh(context, applicationArguments);
        17. stopWatch.stop();
        18. if (this.logStartupInfo) {
        19.     new StartupInfoLogger(this.mainApplicationClass)
                        .logStarted(getApplicationLog(), stopWatch);
            }
        20. listeners.started(context);
        21. callRunners(context, applicationArguments);
        }
        catch (Throwable ex) {
        22. handleRunFailure(context, ex, exceptionReporters, listeners);
            throw new IllegalStateException(ex);
        }

        try {
        23. listeners.running(context);
        }
        catch (Throwable ex) {
        24. handleRunFailure(context, ex, exceptionReporters, null);
            throw new IllegalStateException(ex);
        }
        return context;
    }

本章主要解析1-7小节。

首先返回的对象ConfigurableApplicationContext 就是applicationContext子类,前者相比后者提供了更多的功能,比如实现Lifecycle, Closeable接口 更好的管理bean的声明周期,还有其他的 诸如:addBeanFactoryPostProcessor,setParent,setId,addApplicationListener,addProtocolResolver等额外的功能。

StopWatch 主要是spring为了计算加载耗时产生的。

其内部包含一个list(代表任务的个数),当开始调用start方法后,然后调用stop,都会记录当前时间和start时间的耗时,然后封装成一个任务对象加入到StopWatch内部的list中,其中start和stop方法必须成对出现。

SpringBootExceptionReporter---用来支持报告关于启动的错

首先其会在第13行代码从配置文件中获取具体的实现类,当springboot启动工程出现异常,比如22,24行时候,就会调用handleRunFailure方法,具体如下:

    private void handleRunFailure(ConfigurableApplicationContext context,
            Throwable exception,
            Collection exceptionReporters,
            SpringApplicationRunListeners listeners) {
        try {
            try {
                handleExitCode(context, exception);
                if (listeners != null) {
                    listeners.failed(context, exception);
                }
            }
            finally {
                reportFailure(exceptionReporters, exception);
                if (context != null) {
                    context.close();
                }
            }
        }
        catch (Exception ex) {
            logger.warn("Unable to close ApplicationContext", ex);
        }
        ReflectionUtils.rethrowRuntimeException(exception);
    }

首先看handleExitCode(context, exception)

private void handleExitCode(ConfigurableApplicationContext context,
            Throwable exception) {
        int exitCode = getExitCodeFromException(context, exception);
        if (exitCode != 0) {
            if (context != null) {
                context.publishEvent(new ExitCodeEvent(context, exitCode));
            }
            SpringBootExceptionHandler handler = getSpringBootExceptionHandler();
            if (handler != null) {
                handler.registerExitCode(exitCode);
            }
        }
    }

上述代码的意思就是从异常中获取退出状态码,如果退出状态码不等于0,就通过ConfigurableApplicationContext 发布退出事件,SpringBootExceptionHandler 注册下该状态码。
下面主要看reportFailure(exceptionReporters, exception);

    private void reportFailure(Collection exceptionReporters,
            Throwable failure) {
        try {
            for (SpringBootExceptionReporter reporter : exceptionReporters) {
                if (reporter.reportException(failure)) {
                    registerLoggedException(failure);
                    return;
                }
            }
        }
        catch (Throwable ex) {
            // Continue with normal handling of the original failure
        }
        if (logger.isErrorEnabled()) {
            logger.error("Application run failed", failure);
            registerLoggedException(failure);
        }
    }

上述代码就是依次调用SpringBootExceptionReporter的reportException方法(该方法主要是调用analyzer的集合去分析异常,如果有analyzer能分析成功,就把异常打印出来) 如果成功了在把改异常注册到SpringBootExceptionHandler中。

configureHeadlessProperty();

主要是用来设置headless模式,具体的好处如下

Headless模式是在缺少显示屏、键盘或者鼠标是的系统配置。在java.awt.toolkit和java.awt.graphicsenvironment类中有许多方法,除了对字体、图形和打印的操作外还可以调用显示器、键盘和鼠标的方法。但是有一些类中,比如Canvas和Panel,可以在headless模式下执行
如果名字为java.awt.headless的系统属性被设置true,那么headless工具包就会被使用。应用程序可以执行如下操作:

(1)创建轻量级组件。

(2)收集关于可用的字体、字体指标和字体设置的信息。

(3)设置颜色来渲染准备图片。

(4)创造和获取图像,为渲染准备图片。

(5)使用java.awt.PrintJob,java.awt.print.,和javax.print.类里德打印

SpringApplicationRunListeners

首先SpringApplicationRunListeners是一个集合类,内部包含一个log和包含SpringApplicationRunListener的List。
SpringApplicationRunListener主要是监听SpringApplication对象的,里面的方法都定义了在何时调用SpringApplicationRunListener的各种方法。

下面的每一个方法SpringApplicationRunListener 都把其包装成一个事件,在spring容器还未成功refreshed之前都是使用SimpleApplicationEventMulticaster 去寻找对该事件感兴趣的ApplicationListener,然后调用其onApplicationEvent方法

  • 1.starting:当SpringApplication对象的run方法刚启动的时候(依靠SimpleApplicationEventMulticaster)

  • 2.environmentPrepared:在environment Prepared 但是spring容器还未创建的时候(依靠SimpleApplicationEventMulticaster)

  • 3.contextPrepared:当spring容器已经创建且准备好了,(目前是空的实现)

  • 4.contextLoaded:当spring容器已经loaded 且未refresh 。load就是将我们的primaryClass注册到spring容器中,(依靠SimpleApplicationEventMulticaster) 同时将之前获取到的ApplicationListener都加入到spring容器中,此时如果ApplicationListener还是ApplicationContextAware的也要调用其setApplicationContext方法。

  • 5.started:spring容器已经刷新过且应用已经启动,但是CommandLineRunners和ApplicationRunners还为调用,直接通过spring容器自己发送(因为ApplicationListener已经加入spring容器)

  • 6.running:我们已经调用了CommandLineRunners,直接通过spring容器自己发送(因为ApplicationListener已经加入spring容器)

  • 7.failed:当异常发生的时候就调用这个,如果spring容器没有loaded 或者没有激活就使用SimpleApplicationEventMulticaster,否则还是依靠spring容器自己

SpringApplicationRunListener,ApplicationListener和SimpleApplicationEventMulticaster的区别

  • 1.SpringApplicationRunListener的那些方法底层还是依靠spring容器去发布事件
  • 2.底层还是会被ApplicationListener给监听到
  • 3.在spring容器prepareContext调用之后会将ApplicationListener都加入到SimpleApplicationEventMulticaster,在这之后所有的事件都会lazy发送,即先存在earlyApplicationEvents。等到spring容器refresh之后注册所有ApplicationListener,然后在统一发送之前存储的事件。

总结:本章主要介绍了SpringApplicationRunListener以及其相关方法

你可能感兴趣的:(springboot启动解析二)