Springboot的版本是1.5.19.RELEASE。html
Springboot中會使用FilterRegistrationBean來註冊Filter,Filter是Servlet規範裏面的,屬於容器範圍,Springboot中咱們沒有web.xml,那Springboot中,Filter是如何交給Servlet容器的呢?java
以下圖1是FilterRegistrationBean的繼承圖web
圖1spring
javax.servlet.ServletContext從3.0開始,提供了addFilter方法,以下ide
圖2this
咱們來看FilterRegistrationBean的父類AbstractFilterRegistrationBean的onStartup,以下List-1,調用了ServletContext的addFilter方法。spa
List-1debug
@Override public void onStartup(ServletContext servletContext) throws ServletException { Filter filter = getFilter(); Assert.notNull(filter, "Filter must not be null"); String name = getOrDeduceName(filter); if (!isEnabled()) { this.logger.info("Filter " + name + " was not registered (disabled)"); return; } FilterRegistration.Dynamic added = servletContext.addFilter(name, filter); if (added == null) { this.logger.info("Filter " + name + " was not registered " + "(possibly already registered?)"); return; } configure(added); } /** * Return the {@link Filter} to be registered. * @return the filter */ public abstract Filter getFilter();
onStartup方法是接口org.springframework.boot.web.servlet.ServletContextInitializer的方法,那ServletContextInitializer的onStartup在哪被調用了呢,經過debug,是在以下的地方,code
List-2 EmbeddedWebApplicationContext的selfInitialize方法xml
private void selfInitialize(ServletContext servletContext) throws ServletException { prepareEmbeddedWebApplicationContext(servletContext); registerApplicationScope(servletContext); WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), servletContext); for (ServletContextInitializer beans : getServletContextInitializerBeans()) { beans.onStartup(servletContext); } }
遍歷全部的ServletContextInitializer,以後調用onStartup,並將ServletContext做爲參數傳遞。
從圖2能夠看出,能夠往ServletContext中加入Servlet和Listener,那是否有處理Servlet和Listener的RegistrationBean呢,咱們再看源碼,發現ServletRegistrationBean、ServletListenerRegistrationBean、DelegatingFilterProxyRegistrationBean,這三個都和FilterRegistrationBean在同一個package下。
在Springboot2.0.5中是在ServletWebServerApplicationContext中調用ServletContextInitializer.onStartup方法