RequestMappingHandlerMapping--Spring MVC优先级最高的HandlerMapping

DispatcherServlet在启动时会根据配置文件创建HandlerMapping,这些HandlerMapping都实现了Ordered接口,DispatcherServlet实例化所有的HandlerMapping后放到一个集合中,并根据order对HandlerMapping进行排序。

DispatcherServlet在接受请求时会循环遍历有序的HandlerMapping集合,RequestMappingHandlerMapping的order是0,开始接收请求。

RequestMappingHandlerMappin继承AbstractHandlerMethodMapping,AbstractHandlerMethodMapping实现了InitializingBean,在实例化后对调用afterPropertiesSet方法,该方法完成method handler的注册:

Abstracthandlermethodmapping代码:
  1. public void afterPropertiesSet() {  
  2.         initHandlerMethods();  
  3.     }  
  4.   
  5.     /**  
  6.      * Scan beans in the ApplicationContext, detect and register handler methods.  
  7.      * @see #isHandler(Class)  
  8.      * @see #getMappingForMethod(Method, Class)  
  9.      * @see #handlerMethodsInitialized(Map)  
  10.      */  
  11.     protected void initHandlerMethods() {  
  12.         if (logger.isDebugEnabled()) {  
  13.             logger.debug("Looking for request mappings in application context: " + getApplicationContext());  
  14.         }  
  15.   
  16.         String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?  
  17.                 BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :  
  18.                 getApplicationContext().getBeanNamesForType(Object.class));  
  19.   
  20.         for (String beanName : beanNames) {  
  21.             if (isHandler(getApplicationContext().getType(beanName))){  
  22.                 detectHandlerMethods(beanName);  
  23.             }  
  24.         }  
  25.         handlerMethodsInitialized(getHandlerMethods());  
  26.     }  

 

posted @ 2017-02-11 15:37  李世昌  阅读(2124)  评论(0编辑  收藏  举报