SpringBoot嵌入式Servlet容器与定制化组件超详细讲解

 更新时间:2022年10月6日 22:20  点击:214 作者:Decade0712

嵌入式Servlet容器

在Spring Boot中,默认支持的web容器有 Tomcat, Jetty, 和 Undertow

1、原理分析

那么这些web容器是怎么注入的呢?我们一起来分析一下

当SpringBoot应用启动发现当前是Web应用,它会创建一个web版的ioc容器ServletWebServerApplicationContext

这个类下面有一个createWebServer()方法,当执行关键代码ServletWebServerFactory factory = this.getWebServerFactory();时,它会在系统启动的时候寻找 ServletWebServerFactory(Servlet 的web服务器工厂—> 用于生产Servlet 的web服务器)

private void createWebServer() {
    WebServer webServer = this.webServer;
    ServletContext servletContext = this.getServletContext();
    if (webServer == null && servletContext == null) {
        StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create");
        // 获取ServletWebFactory
        ServletWebServerFactory factory = this.getWebServerFactory();
        createWebServer.tag("factory", factory.getClass().toString());
        // 这里会去调用系统中获取到的web容器工厂类的getWebServer()方法
        this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});
        createWebServer.end();
        this.getBeanFactory().registerSingleton("webServerGracefulShutdown", new WebServerGracefulShutdownLifecycle(this.webServer));
        this.getBeanFactory().registerSingleton("webServerStartStop", new WebServerStartStopLifecycle(this, this.webServer));
    } else if (servletContext != null) {
        try {
            this.getSelfInitializer().onStartup(servletContext);
        } catch (ServletException var5) {
            throw new ApplicationContextException("Cannot initialize servlet context", var5);
        }
    }
    this.initPropertySources();
}

获取ServletWebFactory

protected ServletWebServerFactory getWebServerFactory() {
    String[] beanNames = this.getBeanFactory().getBeanNamesForType(ServletWebServerFactory.class);
    if (beanNames.length == 0) {
        throw new MissingWebServerFactoryBeanException(this.getClass(), ServletWebServerFactory.class, WebApplicationType.SERVLET);
    } else if (beanNames.length > 1) {
        throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to multiple ServletWebServerFactory beans : " + StringUtils.arrayToCommaDelimitedString(beanNames));
    } else {
        return (ServletWebServerFactory)this.getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class);
    }
}

SpringBoot底层默认有很多的WebServer工厂:TomcatServletWebServerFactory,,JettyServletWebServerFactoryUndertowServletWebServerFactory

那么究竟返回哪一个工厂呢?

我们需要分析一下底层的自动配置类,ServletWebServerFactoryAutoConfiguration

@AutoConfiguration
@AutoConfigureOrder(-2147483648)
@ConditionalOnClass({ServletRequest.class})
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
@EnableConfigurationProperties({ServerProperties.class})
@Import({ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class, EmbeddedTomcat.class, EmbeddedJetty.class, EmbeddedUndertow.class})
public class ServletWebServerFactoryAutoConfiguration {
    public ServletWebServerFactoryAutoConfiguration() {
    }
    ...

它引入了一个配置类ServletWebServerFactoryConfiguration,这个类里面会根据动态判断系统中到底导入了那个Web服务器的包,然后去创建对应的web容器工厂,spring-boot-starter-web这个依赖默认导入tomcat,所以我们系统会创建TomcatServletWebServerFactory,由这个工厂创建tomcat容器并启动

一旦我们获取到web Server的工厂类,createWebServer()方法就会去调用this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});

根据断点一直深入,我们可以发现,Tomcat, Jetty, 和 Undertow的工厂类最后都会去调用getWebServer()方法,设置了链接参数,例如TomcatServletWebServerFactorygetWebServer()方法

在方法的最后,它会执行return this.getTomcatWebServer(tomcat);,跟着断点深入,我们发现它会去调用对应web容器类的构造方法,如TomcatWebServer的构造方法,启动tomcat容器

public TomcatWebServer(Tomcat tomcat, boolean autoStart, Shutdown shutdown) {
    this.monitor = new Object();
    this.serviceConnectors = new HashMap();
    Assert.notNull(tomcat, "Tomcat Server must not be null");
    this.tomcat = tomcat;
    this.autoStart = autoStart;
    this.gracefulShutdown = shutdown == Shutdown.GRACEFUL ? new GracefulShutdown(tomcat) : null;
    // 初始化方法initialize---会调用this.tomcat.start();启动容器
    this.initialize();
}

2、Servlet容器切换

Spring Boot默认使用的是tomcat容器,那如果我们想要使用Undertow应该如何切换呢

只需要修改pom文件即可,排除web启动器中tomcat相关的依赖

然后导入Undertow相关启动器

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

3、定制Servlet容器配置

如果想要自己定义一个Servlet容器,可以通过哪些途径呢?

  • 通过分析ServletWebServerFactoryAutoConfiguration绑定了ServerProperties配置类可知,我们想要修改容器的配置,只需要修改配置文件中对应的server.xxx配置项即可
  • 创建一个配置类,通过@Configuration+@Bean的方式,向容器中注入一个ConfigurableServletWebServerFactory类的实现类,ConfigurableServletWebServerFactoryServletWebServerFactory类的子类,提供了很多方法供我们使用

代码样例如下

package com.decade.config;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig {
    @Bean
    public ConfigurableServletWebServerFactory defineWebServletFactory() {
        final TomcatServletWebServerFactory tomcatServletWebServerFactory = new TomcatServletWebServerFactory();
        tomcatServletWebServerFactory.setPort(8081);
        return tomcatServletWebServerFactory;
    }
}

自定义一个ServletWebServerFactoryCustomizer类,它的下面有一个customize()方法,能把配置文件的值和ServletWebServerFactory 进行绑定

Spring官网提供的样例如下

Spring中有很多xxxxxCustomizer,它的作用是定制化器,可以改变xxxx的默认规则

定制化组件

结合之前的原理分析过程可知,我们分析一个组件的过程可以概括为:

导入对应启动器xxx-starter---->分析xxxAutoConfiguration---->导入xxx组件---->绑定xxxProperties配置类----->绑定配置项

那么如果我们要定制化组件,例如自定义参数解析器或者应用启动端口等,可以怎么做呢?

  • 修改配置文件 server.xxx
  • 参考上面编写一个xxxxxCustomizer类
  • 编写自定义的配置类xxxConfiguration:使用@Configuration + @Bean替换、增加容器中默认组件
  • 如果是Web应用,编写一个配置类实现WebMvcConfigurer接口,重写对应方法即可定制化web功能,或者使用@Bean给容器中再扩展一些组件(这条是最重要的)

注意:@EnableWebMvc + 实现WebMvcConfigurer接口:配置类中定义的@Bean可以全面接管SpringMVC,所有规则全部自己重新配置

原理:

  • WebMvcAutoConfiguration类是SpringMVC的自动配置功能类。配置了静态资源、欢迎页…
  • 一旦使用@EnableWebMvc会,@Import(DelegatingWebMvcConfiguration.class)

DelegatingWebMvcConfiguration类的作用是:只保证SpringMVC最基本的使用

  • public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport表明它是WebMvcConfigurationSupport的子类
  • 它会把所有系统中的 WebMvcConfigurer的实现类拿过来,所有功能的定制都是这些WebMvcConfigurer的实现类合起来一起生效

WebMvcConfigurationSupport自动配置了一些非常底层的组件,例如RequestMappingHandlerMapping,这些组件依赖的其他组件都是从容器中获取的,例如ContentNegotiationManager等

由代码可知,WebMvcAutoConfiguration里面的配置要能生效必须系统中不存在WebMvcConfigurationSupport类,所以,一旦配置类上加了@EnableWebMvc,就会导致WebMvcAutoConfiguration没有生效

到此这篇关于SpringBoot嵌入式Servlet容器与定制化组件超详细讲解的文章就介绍到这了,更多相关SpringBoot Servlet容器内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://blog.csdn.net/Decade0712/article/details/127025304

[!--infotagslink--]

相关文章

  • 解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题

    这篇文章主要介绍了解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-04-28
  • SpringBoot实现excel文件生成和下载

    这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • 详解springBoot启动时找不到或无法加载主类解决办法

    这篇文章主要介绍了详解springBoot启动时找不到或无法加载主类解决办法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-16
  • SpringBoot集成Redis实现消息队列的方法

    这篇文章主要介绍了SpringBoot集成Redis实现消息队列的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-10
  • 解决Springboot get请求是参数过长的情况

    这篇文章主要介绍了解决Springboot get请求是参数过长的情况,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-17
  • Spring Boot项目@RestController使用重定向redirect方式

    这篇文章主要介绍了Spring Boot项目@RestController使用重定向redirect方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-02
  • Springboot+TCP监听服务器搭建过程图解

    这篇文章主要介绍了Springboot+TCP监听服务器搭建过程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-10-28
  • springBoot 项目排除数据库启动方式

    这篇文章主要介绍了springBoot 项目排除数据库启动方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-10
  • 详解SpringBoot之访问静态资源(webapp...)

    这篇文章主要介绍了详解SpringBoot之访问静态资源(webapp...),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-14
  • SpringBoot接口接收json参数解析

    这篇文章主要介绍了SpringBoot接口接收json参数解析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-10-19
  • springboot中使用@Transactional注解事物不生效的坑

    这篇文章主要介绍了springboot中使用@Transactional注解事物不生效的原因,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-26
  • springboot多模块包扫描问题的解决方法

    这篇文章主要介绍了springboot多模块包扫描问题的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-16
  • Springboot mybatis plus druid多数据源解决方案 dynamic-datasource的使用详解

    这篇文章主要介绍了Springboot mybatis plus druid多数据源解决方案 dynamic-datasource的使用,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-11-18
  • Springboot+MDC+traceId日志中打印唯一traceId

    本文主要介绍了Springboot+MDC+traceId日志中打印唯一traceId,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-10-17
  • Springboot实现多线程注入bean的工具类操作

    这篇文章主要介绍了Springboot实现多线程注入bean的工具类操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-27
  • 教你使用Portainer管理多台Docker容器环境的方法

    这篇文章主要介绍了Portainer管理多台Docker容器环境,本文给大家介绍的非常详细,包括环境准备及管理docker的详细过程,需要的朋友可以参考下...2021-11-11
  • SpringBoot部署到Linux读取resources下的文件及遇到的坑

    本文主要给大家介绍SpringBoot部署到Linux读取resources下的文件,在平时业务开发过程中,很多朋友在获取到文件内容乱码或者文件读取不到的问题,今天给大家分享小编遇到的坑及处理方案,感兴趣的朋友跟随小编一起看看吧...2021-06-21
  • 关于springboot中nacos动态路由的配置

    这篇文章主要介绍了springboot中nacos动态路由的配置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-11
  • SpringBoot高版本修改为低版本时测试类报错的解决方案

    这篇文章主要介绍了SpringBoot高版本修改为低版本时测试类报错的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-18
  • 解决Springboot整合shiro时静态资源被拦截的问题

    这篇文章主要介绍了解决Springboot整合shiro时静态资源被拦截的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-26