<!-- 配置DispatcherServlet --> <servlet> <servlet-name>springmvc</servlet-name> <!-- DispatcherServlet類的全限定類名 --> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- DispatcherServlet類的初始化參數 --> <param-name>contextConfigLocation</param-name> <!-- 初始化參數的值,即springmvc配置文件的路徑 --> <param-value>classpath:springmvc-config.xml</param-value> </init-param> <!-- 表示web應用啟動即加載該servlet --> <load-on-startup>1</load-on-startup> </servlet> <!-- servlet-mapping,用於攔截所有請求。即所有請求都攔截到該sevlet --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
上面是在web.xml配置文件中加載springmvc配置文件生成webapplicationcontext容器的經典配置。
我們可以看到,在web應用一啟動,該DispatcherServlet就被加載了,加載的時候提供了contextConfigLoacation的初始值,然后通過類的全限定類名使用反射加載該類。
/** * Set the context config location explicitly, instead of relying on the default * location built from the namespace. This location string can consist of * multiple locations separated by any number of commas and spaces. */ public void setContextConfigLocation(String contextConfigLocation) { this.contextConfigLocation = contextConfigLocation; }
以上代碼是在DispatcherSevlet父類FrameworkServlet中,可以看到提供contextConfigloaction后該類就有了srpingmvc配置文件路徑。
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) { Class<?> contextClass = getContextClass(); if (this.logger.isDebugEnabled()) { this.logger.debug("Servlet with name '" + getServletName() + "' will try to create custom WebApplicationContext context of class '" + contextClass.getName() + "'" + ", using parent context [" + parent + "]"); } if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) { throw new ApplicationContextException( "Fatal initialization error in servlet with name '" + getServletName() + "': custom WebApplicationContext class [" + contextClass.getName() + "] is not of type ConfigurableWebApplicationContext"); } ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass); wac.setEnvironment(getEnvironment()); wac.setParent(parent); wac.setConfigLocation(getContextConfigLocation()); configureAndRefreshWebApplicationContext(wac); return wac; }
以上代碼是DispatcherSevlet父類FrameworkServlet中的創造webapplicationcontext的方法,在方法中可以看到獲得剛剛設置的springmvc配置文件的路徑,並且set到ConfigurableWebApplicationContext用於創建容器。
大體流程就是這樣,現在做下小總結:
當web應用啟動的時候配置在web.xml中的DisPartcherServlet就被加載,怎么被加載的呢?
通過提供該類的全限定類名和初始化參數使用反射加載。加載后生成了webApplicationContext容器,
通過該容器就可以使用ioc、aop等spring功能了。需要說明的是該容器的生成需要sevlectContext,
因此必須得再擁有web容器的前提下才能加載webApplicationContext容器。因此,即使它繼承自
applicationContext,因此它的初始化方式也與applicationContext和BeanFactory不同