http://www.javashuo.com/article/p-mbkpimnl-cg.htmlhtml
上一篇文章中,咱們看到了DispatcherServlet和DispatcherServletRegistrationBean這兩個Bean的自動配置。DispatcherServlet咱們很熟悉,DispatcherServletRegistrationBean負責將DispatcherServlet註冊到ServletContext當中。api
既然該類的職責是負責註冊DispatcherServlet,那麼咱們得知道何時觸發註冊操做。爲此,咱們先看看DispatcherServletRegistrationBean這個類的類圖ide
咱們看到,最上面是一個ServletContextInitializer接口。咱們能夠知道,實現該接口意味着是用來初始化ServletContext的。咱們看看該接口this
public interface ServletContextInitializer { void onStartup(ServletContext servletContext) throws ServletException; }
看看RegistrationBean是怎麼實現onStartup方法的spa
@Override 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); }
調用了內部register方法,跟進它code
protected abstract void register(String description, ServletContext servletContext);
這是一個抽象方法htm
再看DynamicRegistrationBean是怎麼實現register方法的blog
@Override 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); }
跟進addRegistration方法接口
protected abstract D addRegistration(String description, ServletContext servletContext);
同樣是一個抽象方法ip
再看ServletRegistrationBean是怎麼實現addRegistration方法的
@Override protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) { String name = getServletName(); return servletContext.addServlet(name, this.servlet); }
咱們看到,這裏直接將DispatcherServlet給add到了servletContext當中。
總的來講,其實就是觸發了初始化ServletContext時候的回調接口onStartup方法,然後直接將DispatcherServlet做爲一個Servlet給add到ServletContext當中。