深入学习 Spring Boot:Spring Boot启动分析(下)

文接 深入学习 Spring Boot:Spring Boot启动分析(上)


2、启动 Spring 应用程序run()

Spring Boot首先帮我们实例化了一个SpringApplication对象,接下类调用这个对象的run方法,创建和刷新一个新的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);
    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);
        listeners.finished(context, null);
        stopWatch.stop();
        if (this.logStartupInfo) {
            new StartupInfoLogger(this.mainApplicationClass)
                    .logStarted(getApplicationLog(), stopWatch);
        }
        return context;
    }
    catch (Throwable ex) {
        handleRunFailure(context, listeners, exceptionReporters, ex);
        throw new IllegalStateException(ex);
    }
}
  • 2.1 启动一个StopWatch测量程序的运行时间。StopWatch可以在开发和调试阶段验证程序的性能

  • 2.2 使用Headless模式:

System.setProperty("java.awt.headless",System.getProperty("java.awt.headless", true);

Headless模式是系统的一种配置模式。在该模式下,系统缺少了显示设备、键盘或鼠标。Spring Boot程序一般是服务端程序,服务器往往缺少前述硬件,但又需要使用他们提供的功能,生成相应的数据,以提供给客户端(比如在console生成spring神兽,绘制验证码之类的)。此时,我们可以在程序开始激活headless模式,告诉程序,现在你要工作在Headless mode下,就不要指望硬件帮忙了,你得自力更生,依靠系统的计算能力模拟出这些特性来。

  • 2.3 通过SpringFactoriesLoader加载SpringApplicationRunListener
    并启动,用以监听SpringApplication的run方法产生的各类事件。SpringApplicationRunListeners是对SpringApplicationRunListener实例集合的一个封装。在这里,SpringApplication只加载了一个Listener:EventPublishingRunListener,事实上这个类是充当着事件广播器的作用,它可以将run方法中的事件(如starting、environmentPrepared)封装为Event对象,发布到我们之前加载的ApplicationListener中。

  • 2.4 创建和配置ConfigurableEnvironment:

private ConfigurableEnvironment prepareEnvironment(
        SpringApplicationRunListeners listeners,
        ApplicationArguments applicationArguments) {
    // Create and configure the environment
    ConfigurableEnvironment environment = getOrCreateEnvironment();
    configureEnvironment(environment, applicationArguments.getSourceArgs());
    listeners.environmentPrepared(environment);
    bindToSpringApplication(environment);
    if (this.webApplicationType == WebApplicationType.NONE) {
        environment = new EnvironmentConverter(getClassLoader())
                .convertToStandardEnvironmentIfNecessary(environment);
    }
    ConfigurationPropertySources.attach(environment);
    return environment;
}

a、根据我们之前检测出来的webApplicationType创建一个ConfigurableEnvironment对象(若this.webApplicationType == WebApplicationType.SERVLET则创建其子类StandardServletEnvironment()对象,否则创建StandardEnvironment对象)。在实例化一个ConfigurableEnvironment对象时,程序会读取运行环境的各种数据,如"java.vm.version" -> "25.73-b02";
b、将我们在启动应用程序时带入的参数(如“--debug”),配置到ConfigurableEnvironment对象中;
c、调用listeners.environmentPrepared(environment),发布事件。在这里,EventPublishingRunListener会封装一个ApplicationEnvironmentPreparedEvent,然后发布到各个Listener中。Listener执行的动作我们暂时不分析,明显可以看到的就是在debug模式下,console会打印第一行日志,显示应用程序的运行环境;
d、将environment绑定到SpringApplication上
e、在environment.propertySources中添加(如果没有的话)一个ConfigurationPropertySourcesPropertySource对象,使得environment管理的PropertySource对象能适配 PropertySourcesPropertyResolver,能够通过属性名get到具体的配置,详细见 ConfigurationPropertySources

  • 2.5 将系统属性“spring.beaninfo.ignore”设置为true,跳过扫描BeanInfo类,防止重复加载bean。详见IGNORE_BEANINFO_PROPERTY_NAME

  • 2.6 调用printBanner打印“Spring神兽”

  • 2.7 根据webApplicationType创建一个ConfigurableApplicationContext对象。在本例中,webApplicationType为”SERVLET“,创建的对象为"org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext"

  • 2.8 加载spring.factories中的SpringBootExceptionReporter实现类

  • 2.9 准备Context:

private void prepareContext(ConfigurableApplicationContext context,
                            ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
                            ApplicationArguments applicationArguments, Banner printedBanner) {
    context.setEnvironment(environment);
    postProcessApplicationContext(context);
    applyInitializers(context);
    listeners.contextPrepared(context);
    if (this.logStartupInfo) {
        logStartupInfo(context.getParent() == null);
        logStartupProfileInfo(context);
    }

    // Add boot specific singleton beans
    context.getBeanFactory().registerSingleton("springApplicationArguments",
            applicationArguments);
    if (printedBanner != null) {
        context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
    }

    // Load the sources
    Set<Object> sources = getAllSources();
    Assert.notEmpty(sources, "Sources must not be empty");
    load(context, sources.toArray(new Object[sources.size()]));
    listeners.contextLoaded(context);
}

a、setEnvironment(environment)
b、postProcessApplicationContext(context),做一些善后工作:如果成员变量beanNameGenerator不为Null,那么为ApplicationContext对象注册beanNameGenerator bean;如果成员变量resourceLoader不为null,则为ApplicationContext对象设置ResourceLoader。

protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
    if (this.beanNameGenerator != null) {
        context.getBeanFactory().registerSingleton(
                AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR,
                this.beanNameGenerator);
    }
    if (this.resourceLoader != null) {
        if (context instanceof GenericApplicationContext) {
            ((GenericApplicationContext) context)
                    .setResourceLoader(this.resourceLoader);
        }
        if (context instanceof DefaultResourceLoader) {
            ((DefaultResourceLoader) context)
                    .setClassLoader(this.resourceLoader.getClassLoader());
        }
    }
}

c、依次调用SpringApplication的initializers中的初始化器:

protected void applyInitializers(ConfigurableApplicationContext context) {
    for (ApplicationContextInitializer initializer : getInitializers()) {
        Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(
                initializer.getClass(), ApplicationContextInitializer.class);
        Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
        initializer.initialize(context);
    }
}

在本例中,initializers列表及其任务为:

initializers = {ArrayList@952}  size = 6
// 读取key为”context.initializer.classes“的配置,实例化Initializer并执行initialize();
 0 = {DelegatingApplicationContextInitializer@1057} 
// 设置context的id,本例等于”application“;
 1 = {ContextIdApplicationContextInitializer@1058} 
// 为context.beanFactoryPostProcessor增加一个ConfigurationWarningsPostProcessor对象,报告warning等级的错误配置
2 = {ConfigurationWarningsApplicationContextInitializer@1059} 
// 为context添加一个ApplicationListener,监听WebServerInitializedEvent
 3 = {ServerPortInfoApplicationContextInitializer@1060} 
// 为context.beanFactoryPostProcessor增加一个CachingMetadataReaderFactoryPostProcessor
 4 = {SharedMetadataReaderFactoryContextInitializer@1061} 
//为context添加一个AutoConfigurationReportListener,用以监听自动配置报告
 5 = {AutoConfigurationReportLoggingInitializer@1062} 

d、调用监听器,报告contextPrepared事件;
e、打印启动日志:

2017-09-10 20:18:51.937  INFO 28314 --- [           main] com.zhuangqf.learn.App                   : Starting App on zhuangqinfa with PID 28314 (/home/zhuangqf/workspace/spring/SpringBootDemo/target/classes started by zhuangqf in /home/zhuangqf/workspace/spring/SpringBootDemo)
2017-09-10 20:18:51.939  INFO 28314 --- [           main] com.zhuangqf.learn.App                   : No active profile set, falling back to default profiles: default

f、注册指定的bean:"springApplicationArguments"和"springBootBanner":

// Add boot specific singleton beans
context.getBeanFactory().registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
    context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
}

简单而言, context的beanFactory是一个DefaultListableBeanFactory对象,其内部有多个Map<String, Object> 用来存放注册的bean。
g、加载context.primarySources,在本例中为App.class,其主要是加载App上的注解或默认的配置文件。

  • 2.10 refreshContext(context)
    加载或刷新持久化形式的配置(如xml文件、properties文件,和数据库信息)。
    由于这是一个启动方法, 如果它失败了, 它应该销毁已经创建的单例, 以避免悬空的资源。换言之, 在调用该方法之后, 所有的单例bean都不应实例化。
@Override
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // Prepare this context for refreshing.
        prepareRefresh();

        // Tell the subclass to refresh the internal bean factory.
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

        // Prepare the bean factory for use in this context.
        prepareBeanFactory(beanFactory);

        try {
            // Allows post-processing of the bean factory in context subclasses.
            postProcessBeanFactory(beanFactory);

            // Invoke factory processors registered as beans in the context.
            invokeBeanFactoryPostProcessors(beanFactory);

            // Register bean processors that intercept bean creation.
            registerBeanPostProcessors(beanFactory);

            // Initialize message source for this context.
            initMessageSource();

            // Initialize event multicaster for this context.
            initApplicationEventMulticaster();

            // Initialize other special beans in specific context subclasses.
            onRefresh();

            // Check for listener beans and register them.
            registerListeners();

            // Instantiate all remaining (non-lazy-init) singletons.
            finishBeanFactoryInitialization(beanFactory);

            // Last step: publish corresponding event.
            finishRefresh();
        }

        catch (BeansException ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Exception encountered during context initialization - " +
                        "cancelling refresh attempt: " + ex);
            }

            // Destroy already created singletons to avoid dangling resources.
            destroyBeans();

            // Reset 'active' flag.
            cancelRefresh(ex);

            // Propagate exception to caller.
            throw ex;
        }

        finally {
            // Reset common introspection caches in Spring's core, since we
            // might not ever need metadata for singleton beans anymore...
            resetCommonCaches();
        }
    }
}

整个方法比较复杂,我们一点点解析:
a、准备刷新prepareRefresh(),完成了以下任务:
设置context的startupDate为当前时间;
设置closed标志位为false,active标志为true;
读取Property配置到environment中;
检查environment必设的配置是否为null;
初始化this.earlyApplicationEvents作为存放发布时间的Set
b、obtainFreshBeanFactory() :销毁原有的beanFactory类,并新建一个beanFactory返回
c、prepareBeanFactory(beanFactory):设置beanFactory的各个属性,由AbstractApplicationContext实现;
d、postProcessBeanFactory(beanFactory):对beanFactory根据具体的Context子类设置不同的属性,例如,本例中context的具体类型为ServletWebServerApplicationContext,会在beanFactory中注册一个ServletContextAwareProcessor。
e、invokeBeanFactoryPostProcessors(beanFactory);调用注册到beanFactory中的postRrocessors。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容