springmvc的入口類爲dispatcherServlet,是一個標準的Servlet,在web.xml中配置web
繼承關係以下spring
Servlet有兩大核心方法,init和service設計模式
涉及到初始化,確定是init,可是在DispatcherServlet中並無init方法,那必定是在父類中了,是的,在HttpServletBean中,簡要代碼以下mvc
public final void init() throws ServletException { try { //初始化web.xml中配置的init-parms HttpServletBean.ServletConfigPropertyValues ex = new HttpServletBean.ServletConfigPropertyValues(this.getServletConfig(), this.requiredProperties); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this); ServletContextResourceLoader resourceLoader = new ServletContextResourceLoader(this.getServletContext()); bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.getEnvironment())); this.initBeanWrapper(bw); bw.setPropertyValues(ex, true); } catch (BeansException var4) { } //提供擴展點,讓子類去實現,擴展初始化 this.initServletBean(); }
在FrameworkServlet中,重寫了initServletBean方法,去掉枝節代碼,主幹以下app
protected final void initServletBean() throws ServletException { try { //初始化servlet上下文 this.webApplicationContext = this.initWebApplicationContext(); //提供擴展點 this.initFrameworkServlet(); } catch (Exception var5) { } }
//核心方法,初始化servlet上下文 protected WebApplicationContext initWebApplicationContext() { //經過ServletContext獲取根上下文: //servletContext.getAttribute("org.spring.framwork.web.context.webApplication.ROOT") WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); WebApplicationContext wac = null; if(this.webApplicationContext != null) { wac = this.webApplicationContext; if(wac instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext attrName = (ConfigurableWebApplicationContext)wac; if(!attrName.isActive()) { if(attrName.getParent() == null) { attrName.setParent(rootContext); } this.configureAndRefreshWebApplicationContext(attrName); } } } if(wac == null) { wac = this.findWebApplicationContext(); } if(wac == null) { wac = this.createWebApplicationContext(rootContext); } if(!this.refreshEventReceived) { //提供擴展點,讓子類擴展初始化 this.onRefresh(wac); } if(this.publishContext) { String attrName1 = this.getServletContextAttributeName(); this.getServletContext().setAttribute(attrName1, wac); } return wac; }
在DispatcherServlet中,重寫了onRefresh方法,onRefresh又委託initStrategies方法,擴展了各類SpringMVC的處理策略。ui
protected void initStrategies(ApplicationContext context) { this.initMultipartResolver(context); this.initLocaleResolver(context); this.initThemeResolver(context); this.initHandlerMappings(context); this.initHandlerAdapters(context); this.initHandlerExceptionResolvers(context); this.initRequestToViewNameTranslator(context); this.initViewResolvers(context); this.initFlashMapManager(context); }
至此,初始化也就完畢了。總結一下,this
子類一直在擴展,來完善初始化的功能,這也是模版方法設計模式的應用,更加靈活spa