SpringBoot中Filter bean如何添加到Servlet容器
作者:yagefuma
对于Spring Boot的IOC容器——ServletWebServerApplicationContext,其中的Filter bean,每个Filter bean都会被独立的注册成为Servlet的Filter。大概的注册过程分成2步:
- IOC容器——ServletWebServerApplicationContext将Filter接口的实现类封装成FilterRegistrationBean,放到ServletContextInitializerBeans实例的成员变量initializers变量(LinkedMultiValueMap)中
- 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); } }
2.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()); }
3.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()); ...... }
2.TomcatServletWebServerFactory的getWebServer(...)函数
public WebServer getWebServer(ServletContextInitializer... initializers) { if (this.disableMBeanRegistry) { Registry.disableRegistry(); } ...... // 将前面获取到的所有ServletContextInitializer实例作为参数,传下去 prepareContext(tomcat.getHost(), initializers); return getTomcatWebServer(tomcat); }
3.TomcatServletWebServerFactory的prepareContext(...)
protected void prepareContext(Host host, ServletContextInitializer[] initializers) { ...... // 合并一下 ServletContextInitializer[] initializersToUse = mergeInitializers(initializers); host.addChild(context); // 将前面获取到的所有ServletContextInitializer实例作为参数,传下去 configureContext(context, initializersToUse); postProcessContext(context);}
4.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); ...... }
5.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()); } } }
6.回顾第一章:“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); }
7.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); }
8.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中Filter bean是怎么被添加到Servlet容器中的的文章就介绍到这了,更多相关SpringBoot Filter bean添加到Servlet容器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!