首页 > 其他分享 >SpringBoot中Filter bean是怎么被添加到Servlet容器中的

SpringBoot中Filter bean是怎么被添加到Servlet容器中的

时间:2023-08-04 14:23:07浏览次数:77  
标签:SpringBoot FilterRegistrationBean Filter bean initializers servletContext Servle

参考资料

对于Spring Boot的IOC容器——ServletWebServerApplicationContext,其中的Filter bean,每个Filter bean都会被独立的注册成为Servlet的Filter。大概的注册过程分成2步:

  1. IOC容器——ServletWebServerApplicationContext将Filter接口的实现类封装成FilterRegistrationBean,放到ServletContextInitializerBeans实例的成员变量initializers变量(LinkedMultiValueMap)中
  2. Spring 容器(ServletWebServerApplicationContext)从ServletContextInitializerBeans实例的成员变量initializers变量(LinkedMultiValueMap),中获取所有的ServletContextInitializer实现类,调用它们的onStartUp函数,FilterRegistrationBean的onStartup函数就是在调用ServletContext的addFilter函数向Servlet添加Filter

1. IOC容器——ServletWebServerApplicationContext将Filter接口的实现类封装成FilterRegistrationBean,放到ServletContextInitializerBeans实例的成员变量initializers变量(LinkedMultiValueMap)中

  1. Spring容器——ServletWebServerApplicationContext的refresh()函数被调用。
protected void onRefresh() {
    super.onRefresh();    
    try {
       createWebServer();    
       }
    catch (Throwable ex) {
       throw new ApplicationContextException("Unable to start web server", ex);   
    }
}
  1. ServletWebServerApplicationContext的createWebServer()函数,
  • 在函数中会调用getSelfInitializer()函数获取所有的ServletContextInitializer实例,
  • 而获取所有的ServletContextInitializer实例的过程中,会查找所有实现了Filter接口的bean,并注册成FilterRegistrationBean(实现了ServletContextInitializer接口,所以也属于ServletContextInitializer实例),
  • 然后把FilterRegistrationBean放到initializers变量(LinkedMultiValueMap)中
private void createWebServer() {
    WebServer webServer = this.webServer;    
    ServletContext servletContext = getServletContext();    
    if (webServer == null && servletContext == null) {
       StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create");       
       ServletWebServerFactory factory = getWebServerFactory();       
       createWebServer.tag("factory", factory.getClass().toString());  
       //  getSelfInitializer()函数中获取所有ServletContextInitializer实例,调用onStartup方法完成注册
       this.webServer = factory.getWebServer(getSelfInitializer());
       ......
}

private org.springframework.boot.web.servlet.ServletContextInitializer getSelfInitializer() {
    return this::selfInitialize;
    }

private void selfInitialize(ServletContext servletContext) throws ServletException {
    prepareWebApplicationContext(servletContext);    
    registerApplicationScope(servletContext);    
    WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), servletContext);  
    //   获取所有ServletContextInitializer实例,调用onStartup方法
    for (ServletContextInitializer beans : getServletContextInitializerBeans()) {
       beans.onStartup(servletContext);   
        }
}
// 传入BeanFactory,new 一个ServletContextInitializerBeans对象,这个对象实现了Collection接口,是一个集合,
// 集合内的元素是需要内置在Servlet Context上的ServletContextInitializer bean
protected Collection<ServletContextInitializer> getServletContextInitializerBeans() {
    return new ServletContextInitializerBeans(getBeanFactory());
    }
  1. ServletContextInitializerBeans的构建
public ServletContextInitializerBeans(ListableBeanFactory beanFactory,       Class<? extends ServletContextInitializer>... initializerTypes) {
    this.initializers = new LinkedMultiValueMap<>();    
    this.initializerTypes = (initializerTypes.length != 0) ? Arrays.asList(initializerTypes)
          : Collections.singletonList(ServletContextInitializer.class);    
     // 找直接定义为ServletContextInitializer的bean(比如FilterRegistrationBean),DelegatingFilterProxyRegistrationBean等,
     // 添加到initializers中
    addServletContextInitializerBeans(beanFactory);    
     // 找实现了Filter接口的bean,将他们封装成ServletContextInitializer bean(对于Filter的实现类也就是封装成FilterRegistrationBean),
     // 添加到initializers中
    addAdaptableBeans(beanFactory);   
    //排序  
    List<ServletContextInitializer> sortedInitializers = this.initializers.values().stream()
          .flatMap((value) -> value.stream().sorted(AnnotationAwareOrderComparator.INSTANCE))
          .collect(Collectors.toList());    
          this.sortedList = Collections.unmodifiableList(sortedInitializers);    
          logMappings(this.initializers);
}

protected void addAdaptableBeans(ListableBeanFactory beanFactory) {
    MultipartConfigElement multipartConfig = getMultipartConfig(beanFactory);    
    // 获取实现了Servlet接口的bean
    addAsRegistrationBean(beanFactory, Servlet.class, new ServletRegistrationBeanAdapter(multipartConfig)); 
    // 查找所有实现了Filter接口的bean,并注册成FilterRegistrationBean,
    // 然后把FilterRegistrationBean放到initializers变量(LinkedMultiValueMap)中
    addAsRegistrationBean(beanFactory, Filter.class, new FilterRegistrationBeanAdapter());    
    for (Class<?> listenerType : ServletListenerRegistrationBean.getSupportedTypes()) {
       addAsRegistrationBean(beanFactory, EventListener.class, (Class<EventListener>) listenerType,             
                 new ServletListenerRegistrationBeanAdapter());    
       }
}

所以我们可以看到ServletContextInitializerBeans构造函数是怎么构造一个包含
ServletContextInitializer bean集合的

  • 直接定义为ServletContextInitializer的bean(比如FilterRegistrationBean)
  • DelegatingFilterProxyRegistrationBean等,添加到initializers中
    找实现了Filter接口的bean,将他们封装成ServletContextInitializer bean(对于Filter的实现类也就是封装成FilterRegistrationBean),添加到initializers中
  • 排序然后一并返回

所以ServletContextInitializerBeans实例表示的是:一个从ListableBeanFactory bean容器中获得的ServletContextInitializer实例的集合。这个集合中的每个元素来自容器中定义的每个如下类型的bean :

  • 实现了ServletContextInitializer接口的bean
    具体可能以ServletRegistrationBean/FilterRegistrationBean/EventListenerRegistrationBean的形式存在。这些 bean 设计的目的是用来注册相应的 Servlet/Filter/EventListener bean 到 ServletContext
- **实现了Servlet/Filter/EventListener接口的 bean**

这些 bean直接以实现裸的Servlet/Filter/EventListener接口的 bean的形式存在,但是Springboot会将它们封装成相应的 RegistrationBean(也是ServletContextInitializer ),然后也注册到ServletContext。

也就是说,Spring帮我们将实现裸的Servlet/Filter/EventListener接口的 bean,封装成ServletRegistrationBean/FilterRegistrationBean/EventListenerRegistrationBean。

2. Spring 容器(ServletWebServerApplicationContext)从ServletContextInitializerBeans实例的成员变量initializers变量(LinkedMultiValueMap),中获取所有的ServletContextInitializer实现类,调用它们的startUp函数,FilterRegistrationBean的onStartup函数就是在调用ServletContext的addFilter函数向Servlet添加Filter

  1. 还是要回到上面1.2中的createWebServer()函数中,这次我们不看getSelfInitializer(),而是看factory.getWebServer(...)函数。
private void createWebServer() {
    WebServer webServer = this.webServer;    
    ServletContext servletContext = getServletContext();    
    if (webServer == null && servletContext == null) {
       StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create");       
       ServletWebServerFactory factory = getWebServerFactory();       
       createWebServer.tag("factory", factory.getClass().toString());  
       //  getSelfInitializer()函数中获取所有ServletContextInitializer实例,调用onStartup方法完成注册
       this.webServer = factory.getWebServer(getSelfInitializer());
       ......
}
  1. TomcatServletWebServerFactory的getWebServer(...)函数
public WebServer getWebServer(ServletContextInitializer... initializers) {
    if (this.disableMBeanRegistry) {
       Registry.disableRegistry();    
    }
    ......
    // 将前面获取到的所有ServletContextInitializer实例作为参数,传下去
    prepareContext(tomcat.getHost(), initializers);    
    return getTomcatWebServer(tomcat);
 }
  1. TomcatServletWebServerFactory的prepareContext(...)
protected void prepareContext(Host host, ServletContextInitializer[] initializers) {
    ......
    // 合并一下
    ServletContextInitializer[] initializersToUse = mergeInitializers(initializers);    
    host.addChild(context);   
    // 将前面获取到的所有ServletContextInitializer实例作为参数,传下去 
    configureContext(context, initializersToUse);    
    postProcessContext(context);}
  1. tomcatServletWebServerFactory的configureContext(...),创建了TomcatStarter,并将TomcatStarter绑定到Tomcat上,这样Tomcat启动时就会回调TomcatStarter的onStartup函数
protected void configureContext(Context context, ServletContextInitializer[] initializers) {
    // 将前面获取到的所有ServletContextInitializer实例作为参数,传下去 
    TomcatStarter starter = new TomcatStarter(initializers);
    
    // 下面这一系列操作是将TomcatStarter绑定到Tomcat上,这样TomcatStarter就会在Tomcat启动时被回调
    if (context instanceof TomcatEmbeddedContext) {
    TomcatEmbeddedContext embeddedContext = (TomcatEmbeddedContext) context;    
    embeddedContext.setStarter(starter);    
    embeddedContext.setFailCtxIfServletStartFails(true);
    }
    context.addServletContainerInitializer(starter, NO_CLASSES);
    ......
}
  1. TomcatStarter的startUp函数被调用的时候,就会变量所有的ServletContextInitializer实例的onStartup函数,
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
    try {
       for (ServletContextInitializer initializer : this.initializers) {
          initializer.onStartup(servletContext);       
          }
    }
    catch (Exception ex) {
       this.startUpException = ex;       
       // Prevent Tomcat from logging and re-throwing when we know we can       
       // deal with it in the main thread, but log for information here.      
       if (logger.isErrorEnabled()) {
          logger.error("Error starting Tomcat context. Exception: " + ex.getClass().getName() + ". Message: "                + ex.getMessage());       
          }
    }
}
  1. 回顾第一章:“Filter接口的实现类封装成FilterRegistrationBean”,而FilterRegistrationBean又是ServletContextInitializer接口的实现类,所以上面第5步,也会回调FilterRegistrationBean的onStartup函数,
//FilterRegistrationBean
public final void onStartup(ServletContext servletContext) throws ServletException {
    String description = getDescription();    
    if (!isEnabled()) {
       logger.info(StringUtils.capitalize(description) + " was not registered (disabled)");       return;    
       }
    // 这里
    register(description, servletContext);
}
  1. DynamicRegistrationBean.class
protected final void register(String description, ServletContext servletContext) {
    //这里
    D registration = addRegistration(description, servletContext);    
    if (registration == null) {
       logger.info(StringUtils.capitalize(description) + " was not registered (possibly already registered?)");       
       return;    
       }
    configure(registration);
    }
  1. AbstractFilterRegistrationBean.class, 看到没,最终还是用ServletContext的addFilter函数,向Servlet容器中添加Filter。
protected Dynamic addRegistration(String description, ServletContext servletContext) {
    // getFilter()在FilterRegistrationBean中被实现,返回的就是那个Filter接口的实现类。
    Filter filter = getFilter();   
    // 将Filter接口的实现类添加到Servlet容器中 
    return servletContext.addFilter(getOrDeduceName(filter), filter);
  }

标签:SpringBoot,FilterRegistrationBean,Filter,bean,initializers,servletContext,Servle
From: https://www.cnblogs.com/yagefuma/p/17605798.html

相关文章

  • Java17与相关框架支持版本SpringBoot、IDEA、Tomcat等
    相关框架需要的最低版本NameVersionJava17+SpringFramework6.0SpringBoot3.0Tomcat10.1Maven3.6.3+Gradle7.x(7.5orlater)and8.xUndertow2.3IntelliJIDEA2021.2+SpringFrameworkSpringFrameworkOverview::SpringFrame......
  • 几乎涵盖你需要的SpringBoot所有操作|高清PDF
    SpringBoot目前的使用已经很普遍了,实际的项目中,我们需要集成各种的插件支持,不仅如此,还有很多可能我们平时不知道,但是很方便的操作。pdf里面的东西还是比较全面的。以下是pdf的目录,由于目录过长,所以只截图一部分。中间还有很多目录...另外,去年小咖总结&整理了 Java小咖秀面试手册V2......
  • SpringBoot-日志系统
    1.Logback介绍Logback是由log4j创始人设计的又一个开源日志组件Logback当前分成三个模块:logback-core,logback-classic和logback-accesslogback-core是其它两个模块的基础模块,类似与springframeworklogback-classic是log4j的一个改良版本。此外logback-classic......
  • 【答疑】jsonpath和beanshell配合使用案例
    问题今天提升群小伙伴问了这样一个问题:接口返回如下(list元素个数不确定),需要提取所有的iautoid,然后用逗号拼接起来,如果是如下返回,需要得到的结果是1687283717749342208,1679392630364184576,后续请求需要使用{ "data":{ "firstPage":true, "lastPage":false, "list":......
  • Java反射与自定义注解实现不同Bean属性映射的高效解决方案
    假设现有一个叫user的bean,里面有username、passsword、sex、createTime这四个属性,需要实现一个功能,把其它bean里的字段分别映射到user里的username、passsword、sex、createTime这几个属性上,然后可以根据其它的bean的实例自动转化为user的实例(填充对应属性值),下面是代码实现。Java......
  • .Net Core AlwaysRunResultFilter
    目录作用实现IAlwaysRunResultFilterIAsyncAlwaysRunResultFilterDemoCustomAsyncAlwaysRunResultFilterAttribute.cs全局注册Program.cs作用修改返回值,始终会触发,即使filter已经中断也会执行AlwaysRunFilter任何时刻都会执行一遍,可以在做了缓存的时候(如果有缓存并中......
  • Java面试题 P48:框架篇:Spring框架常见注解(Spring、SpringBoot、SpringMvc)
        ......
  • SpringBoot+MyBatisPlus实现读写分离
    文章目录1、前言2、读写分离原理3、实现步骤3.1.主从复制搭建3.2.配置pom.xml3.3.配置数据源3.4.配置MyBatisPlus3.5.实现读写分离4、总结1、前言随着业务量的不断增长,数据库的读写压力也越来越大。为了解决这个问题,我们可以采用读写分离的方案来分担数据库的读写负载。本......
  • 【SpringBoot学习】7、SpringBoot 整合 JDBC Templete 实现 CRUD 案例
    准备工作数据库CREATETABLE`tb_user`(`id`bigint(20)NOTNULLAUTO_INCREMENTCOMMENT'主键ID',`username`varchar(255)DEFAULTNULLCOMMENT'用户名',`password`varchar(255)DEFAULTNULLCOMMENT'密码',`ctime`datetimeDEFAULT......
  • 【SpringBoot学习】6、SpringBoot 整合 Mybatis 逆向工程和整合 Mybatis
    mybatis逆向工程使用方法springboot整合mybtis逆向工程,我使用的是idea,springboot,maven,eclipse的同理。1、添加所需插件和jar包<plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><dep......