Spring MVC启动过程
1 <!-- servlet定义 -->
2 <servlet>
3 <servlet-name>spring</servlet-name>
4 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
5 <!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml
6 <init-param>
7 <param-name>contextConfigLocation</param-name>
8 <param-value>/WEB-INF/spring-servlet.xml</param-value> 默认
9 </init-param>
10 -->
11 <load-on-startup>1</load-on-startup>
12 </servlet>
13 <servlet-mapping>
14 <servlet-name>spring</servlet-name>
15 <url-pattern>/</url-pattern>
16 </servlet-mapping>
17
18
19 <!-- 指定Spring Bean的配置文件所在目录。ContextLoaderListener会默认查找位于:WEB-INF/下的是否有一个文件名称为:applicationContext.xml
20 如果没有此文件,并且没有配置 下面的contextConfigLocation,则会报错-->
21 <listener>
22 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
23 </listener>
24 <!-- 配置contextConfigLocation初始化参数 -->
25 <context-param>
26 <param-name>contextConfigLocation</param-name>
27 <param-value>/WEB-INF/applicationContext.xml</param-value>
28 </context-param>
DispatcherServlet:前端处理器,接受的HTTP请求和转发请求的类。
applicationContext.xml: 定义WebAppliactionContext上下文中的bean。
contextConfigLocation:指定Spring IoC容器需要读取的定义了非web层的Bean(DAO/Service)的XML文件路径。
ContextLoaderListener:Spring MVC在Web容器中的启动类,负责Spring IoC容器在Web上下文中的初始化。
Spring MVC启动过程大致分为两个过程:1、ContextLoaderListener初始化,实例化IoC容器,并将此容器实例注册到ServletContext中。2、DispatcherServlet初始化。
DispatcherServlet在启动时会根据配置文件创建HandlerMapping,这些 HandlerMapping 都实现了org.springframework.core.Ordered接口,
public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport implements HandlerMapping, Ordered
DispatcherServlet实例化所有的HandlerMapping后放到一个集合中,并根据order对HandlerMapping进行排序。
DispatcherServlet在接受请求时会循环遍历有序的HandlerMapping集合,RequestMappingHandlerMapping的order是0,开始接收请求。



RequestMappingHandlerMappin继承AbstractHandlerMethodMapping,AbstractHandlerMethodMapping实现了InitializingBean,在实例化后对调用afterPropertiesSet方法,该方法完成method handler的注册:
public void afterPropertiesSet() { initHandlerMethods(); } /** * Scan beans in the ApplicationContext, detect and register handler methods. * @see #isHandler(Class) * @see #getMappingForMethod(Method, Class) * @see #handlerMethodsInitialized(Map) */ protected void initHandlerMethods() { if (logger.isDebugEnabled()) { logger.debug("Looking for request mappings in application context: " + getApplicationContext()); } String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ? BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) : getApplicationContext().getBeanNamesForType(Object.class)); for (String beanName : beanNames) { if (isHandler(getApplicationContext().getType(beanName))){ detectHandlerMethods(beanName); } } handlerMethodsInitialized(getHandlerMethods()); }

浙公网安备 33010602011771号