Springboot之FilterRegistrationBean

    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下。

  • ServletRegistrationBean的onStartup方法中調用servletContext.addServlet方法將Servlet加入到ServletContext中;
  • ServletListenerRegistrationBean的onStartup方法中調用servletContext.addListener方法將Listener加入到ServletContext中;
  • DelegatingFilterProxyRegistrationBean則是將DelegatingFilterProxy註冊到Servlet3.0+的容器中,若是在web.xml中使用Springsecurity,那麼DelegatingFilterProxy必定使用過,底層上會去Spring的上下文中查找指定的bean(根據String類型的beanName)。

    在Springboot2.0.5中是在ServletWebServerApplicationContext中調用ServletContextInitializer.onStartup方法

思考

  1. 有個問題,Springboot啓動時,是在什麼時候調用List-2的呢?

Reference

  1. 源碼
  2. https://www.cnblogs.com/youzhibing/p/9866690.html
相關文章
相關標籤/搜索