← 返回学习路线

SYSTEM

内嵌容器

Java基础内嵌容器system
src/content/notes/system/内嵌容器.md

内嵌容器

SpringBoot 嵌入式 Servlet 容器,默认支持的 WebServe:Tomcat、Jetty、Undertow

配置方式:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion> <!--必须要把内嵌的 Tomcat 容器-->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

Web 应用启动,SpringBoot 导入 Web 场景包 tomcat,创建一个 Web 版的 IOC 容器:

  • SpringApplication.run(BootApplication.class, args):应用启动

  • ConfigurableApplicationContext.run():

    • context = createApplicationContext():创建容器

      • applicationContextFactory = ApplicationContextFactory.DEFAULT

        ApplicationContextFactory DEFAULT = (webApplicationType) -> {
            try {
                switch (webApplicationType) {
                    case SERVLET:
                        // Servlet 容器,继承自 ServletWebServerApplicationContext
                        return new AnnotationConfigServletWebServerApplicationContext();
                    case REACTIVE:
                        // 响应式编程
                        return new AnnotationConfigReactiveWebServerApplicationContext();
                    default:
                        // 普通 Spring 容器
                        return new AnnotationConfigApplicationContext();
                }
            } catch (Exception ex) {
                throw new IllegalStateException();
            }
        }
      • applicationContextFactory.create(this.webApplicationType):根据应用类型创建容器

    • refreshContext(context):容器启动刷新

内嵌容器工作流程:

  • Spring 容器启动逻辑中,在实例化非懒加载的单例 Bean 之前有一个方法 onRefresh(),留给子类去扩展,Web 容器就是重写这个方法创建 WebServer

    protected void onRefresh() {
        //省略....
    	createWebServer();
    }
    private void createWebServer() {
        ServletWebServerFactory factory = getWebServerFactory();
        this.webServer = factory.getWebServer(getSelfInitializer());
        createWebServer.end();
    }

    获取 WebServer 工厂 ServletWebServerFactory,并且获取的数量不等于 1 会报错,Spring 底层有三种:

    TomcatServletWebServerFactory、JettyServletWebServerFactory、UndertowServletWebServerFactory

  • 自动配置类 ServletWebServerFactoryAutoConfiguration 导入了 ServletWebServerFactoryConfiguration(配置类),根据条件装配判断系统中到底导入了哪个 Web 服务器的包,创建出服务器并启动

  • 默认是 web-starter 导入 tomcat 包,容器中就有 TomcatServletWebServerFactory,创建出 Tomcat 服务器并启动,

    public TomcatWebServer(Tomcat tomcat, boolean autoStart, Shutdown shutdown) {
    	// 初始化
       	initialize();
    }

    初始化方法 initialize 中有启动方法:this.tomcat.start()