美文网首页
springboot源码走读之一

springboot源码走读之一

作者: 海蟾子_null | 来源:发表于2019-11-14 23:59 被阅读0次

前面的话

首先一个最简单的springboot的例子引入本主题。

@SpringBootApplication
public class StudyApplication {
    public static void main(String[] args) {
        SpringApplication.run(StudyApplication.class);
    }
}

其中包依赖也是最简单的。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.spring.study</groupId>
    <artifactId>spring-study</artifactId>
    <version>1.0-SNAPSHOT</version>

<dependencies>
    <!--<dependency>-->
        <!--<groupId>org.springframework.boot</groupId>-->
        <!--<artifactId>spring-boot-starter</artifactId>-->
        <!--<version>2.2.1.RELEASE</version>-->
    <!--</dependency>-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.2.1.RELEASE</version>
    </dependency>
</dependencies>
</project>

这里就使用springboot的web方式,引入当前最新版本2.2.1.
直接指向main方法,就可以启动一个简单的springboot,端口使用默认的8080。
例子有了,就可以直接debug代码,走读之。

springboot启动过程代码走读

run方法的实现代码如下:

/**
     * Static helper that can be used to run a {@link SpringApplication} from the
     * specified sources using default settings and user supplied arguments.
     * @param primarySources the primary sources to load
     * @param args the application arguments (usually passed from a Java main method)
     * @return the running {@link ApplicationContext}
     */
    public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
        return new SpringApplication(primarySources).run(args);
    }

接下来看如何初始化SpringApplication

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
        this.resourceLoader = resourceLoader;
        Assert.notNull(primarySources, "PrimarySources must not be null");
        this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
        this.webApplicationType = WebApplicationType.deduceFromClasspath();
        setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
        setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
        this.mainApplicationClass = deduceMainApplicationClass();
    }

从代码可以看出,这里主要做了如下几件事情:

  1. 确定当前应用类型。deduceFromClasspath .springboot中主要有三种应用类型,分别是 REACTIVE,SERVLET,NONE(普通类型),其中SERVLET是默认类型。
  2. 通过SPI方式,读取spring.factories,设置应用上下文初始化类和ApplicationListener。
  3. 确定程序的入口类

以上,就把SpringApplication的实例创建出来了。
接下来就是看run方法了。
先上代码:

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);
            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;
    }

这里主要做了如下几件事情:

  1. 初始化并启动一个计时器
  2. 设置Headless参数
  3. 通过spi方式初始化springboot启动过程监听。
  4. listeners.starting(); 发送一个ApplicationStartingEvent这个类型的事件。该事件的消费者在springboot中有两个,分别是BackgroundPreinitializerLoggingApplicationListener. BackgroundPreinitializer是springboot异步初始化一些相对耗时的操作,减少启动时间,比如各种类型转换器初始化,校验器初始化,http消息转换器初始化,Jackson转换器初始化等。LoggingApplicationListener主要是初始化日志系统。
  5. 装配参数和准备上下文环境及打印banner图,即我们经常见到的springboot的logo图。
  6. 初始化applicationContext,当我们启动的是一个SERVLET容器时,则applicationContext为org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext,当启动的是一个reactive容器,则初始化为org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext,都不是,则默认为org.springframework.context.annotation.AnnotationConfigApplicationContext
  7. 初始化异常上报类。也是通过spi机制实现的。
  8. prepareContext 主要是做一些applicationContext的前期的初始化工作。如设置environment,设置一些内部使用的bean,调用上文提到的一些上下文初始化类ApplicationContextInitializer。触发ApplicationContextInitializedEvent事件。设置beanFactory相关的参数及加载资源,并触发ApplicationPreparedEvent事件。
  9. refreshContext(context),这一步是最重要的一步,所有的bean初始化,注解的处理都在这一步,这一步与spring的基础功能紧密结合。直接调用spring的入口,refresh()方法。这里只是对整个启动过程做一下介绍,对这块接下来的文章中会有详细的介绍。
  10. afterRefresh后置处理,默认为空方法。
  11. 计时结束。触发ApplicationStartedEvent事件。
  12. 执行ApplicationRunnerCommandLineRunner,这两个接口主要是在容器启动完成后,一些用户定制化的场景。如加载某些配置,建立一些连接等。
    至此,springboot就启动完成了。接下来我们就可以来进入每个步骤进行详细的走读与讨论了。

相关文章

网友评论

      本文标题:springboot源码走读之一

      本文链接:https://www.haomeiwen.com/subject/zxycictx.html