SpringMVC源碼之Controller查找原理

摘要

  • 本文從源碼層面簡單講解SpringMVC的處理器映射環節,也就是查找Controller詳細過程。

SpringMVC請求流程

  • Controller查找在上圖中對應的步驟1至2的過程

SpringMVC初始化過程

理解初始化過程以前,先認識兩個類

  1. RequestMappingInfo類,對RequestMapping註解封裝。裏面包含http請求頭的相關信息。如uri、method、params、header等參數。一個對象對應一個RequestMapping註解
  2. HandlerMethod類,是對Controller的處理請求方法的封裝。裏面包含了該方法所屬的bean對象、該方法對應的method對象、該方法的參數等。
  • 上圖是RequestMappingHandlerMapping的繼承關係。在SpringMVC初始化的時候,首先執行RequestMappingHandlerMapping中的afterPropertiesSet方法,而後會進入AbstractHandlerMethodMapping的afterPropertiesSet方法(line:93),這個方法會進入當前類的initHandlerMethods方法(line:103)。這個方法的職責即是從applicationContext中掃描beans,而後從bean中查找並註冊處理器方法,代碼以下。
protected void initHandlerMethods() {
  if (logger.isDebugEnabled()) {
      logger.debug("Looking for request mappings in application context: " + getApplicationContext());
  }
  //獲取applicationContext中全部的bean name
  String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
        BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
        getApplicationContext().getBeanNamesForType(Object.class));
  //遍歷beanName數組
  for (String beanName : beanNames) {
      //isHandler會根據bean來判斷bean定義中是否帶有Controller註解或RequestMapping註解
      if (isHandler(getApplicationContext().getType(beanName))){
        detectHandlerMethods(beanName);
      }
  }
  handlerMethodsInitialized(getHandlerMethods());
}
  • isHandler方法其實很簡單,以下
@Override
protected boolean isHandler(Class<?> beanType) {
  return ((AnnotationUtils.findAnnotation(beanType, Controller.class) != null) ||
        (AnnotationUtils.findAnnotation(beanType, RequestMapping.class) != null));
}
  • 就是判斷當前bean定義是否帶有Controlller註解或RequestMapping註解,看了這裏邏輯可能會想若是隻有RequestMapping會生效嗎?答案是不會的,由於在這種狀況下Spring初始化的時候不會把該類註冊爲Spring bean,遍歷beanNames時不會遍歷到這個類,因此這裏把Controller換成Compoent註解也是能夠,不過通常不會這麼作。當肯定bean爲handlers後,便會從該bean中查找出具體的handler方法(也就是咱們一般定義的Controller類下的具體定義的請求處理方法),查找代碼以下
protected void detectHandlerMethods(final Object handler) {
  //獲取到當前Controller bean的class對象
  Class<?> handlerType = (handler instanceof String) ?
        getApplicationContext().getType((String) handler) : handler.getClass();
  //同上,也是該Controller bean的class對象
  final Class<?> userType = ClassUtils.getUserClass(handlerType);
  //獲取當前bean的全部handler method。這裏查找的依據即是根據method定義是否帶有RequestMapping註解。若是有根據註解建立RequestMappingInfo對象
  Set<Method> methods = HandlerMethodSelector.selectMethods(userType, new MethodFilter() {
      public boolean matches(Method method) {
        return getMappingForMethod(method, userType) != null;
      }
  });
  //遍歷並註冊當前bean的全部handler method
  for (Method method : methods) {
      T mapping = getMappingForMethod(method, userType);
      //註冊handler method,進入如下方法
      registerHandlerMethod(handler, method, mapping);
  }
}
  • 以上代碼有兩個地方有調用了getMappingForMethod方法
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
  RequestMappingInfo info = null;
   //獲取method的@RequestMapping註解
  RequestMapping methodAnnotation = AnnotationUtils.findAnnotation(method, RequestMapping.class);
  if (methodAnnotation != null) {
      RequestCondition<?> methodCondition = getCustomMethodCondition(method);
      info = createRequestMappingInfo(methodAnnotation, methodCondition);
       //獲取method所屬bean的@RequtestMapping註解
      RequestMapping typeAnnotation = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class);
      if (typeAnnotation != null) {
        RequestCondition<?> typeCondition = getCustomTypeCondition(handlerType);
        //合併兩個@RequestMapping註解
        info = createRequestMappingInfo(typeAnnotation, typeCondition).combine(info);
      }
  }
  return info;
}
  • 這個方法的做用就是根據handler method方法建立RequestMappingInfo對象。首先判斷該mehtod是否含有RequestMpping註解。若是有則直接根據該註解的內容建立RequestMappingInfo對象。建立之後判斷當前method所屬的bean是否也含有RequestMapping註解。若是含有該註解則會根據該類上的註解建立一個RequestMappingInfo對象。而後在合併method上的RequestMappingInfo對象,最後返回合併後的對象。如今回過去看detectHandlerMethods方法,有兩處調用了getMappingForMethod方法,我的以爲這裏是能夠優化的,在第一處判斷method時否爲handler時,建立的RequestMappingInfo對象能夠保存起來,直接拿來後面使用,就少了一次建立RequestMappingInfo對象的過程。而後緊接着進入registerHandlerMehtod方法,以下
protected void registerHandlerMethod(Object handler, Method method, T mapping) {
  //建立HandlerMethod
  HandlerMethod newHandlerMethod = createHandlerMethod(handler, method);
  HandlerMethod oldHandlerMethod = handlerMethods.get(mapping);
  //檢查配置是否存在歧義性
  if (oldHandlerMethod != null && !oldHandlerMethod.equals(newHandlerMethod)) {
      throw new IllegalStateException("Ambiguous mapping found. Cannot map '" + newHandlerMethod.getBean()
            + "' bean method \n" + newHandlerMethod + "\nto " + mapping + ": There is already '"
            + oldHandlerMethod.getBean() + "' bean method\n" + oldHandlerMethod + " mapped.");
  }
  this.handlerMethods.put(mapping, newHandlerMethod);
  if (logger.isInfoEnabled()) {
      logger.info("Mapped \"" + mapping + "\" onto " + newHandlerMethod);
  }
  //獲取@RequestMapping註解的value,而後添加value->RequestMappingInfo映射記錄至urlMap中
  Set<String> patterns = getMappingPathPatterns(mapping);
  for (String pattern : patterns) {
      if (!getPathMatcher().isPattern(pattern)) {
        this.urlMap.add(pattern, mapping);
      }
  }
}
  • 這裏T的類型是RequestMappingInfo。這個對象就是封裝的具體Controller下的方法的RequestMapping註解的相關信息。一個RequestMapping註解對應一個RequestMappingInfo對象。HandlerMethod和RequestMappingInfo相似,是對Controlelr下具體處理方法的封裝。先看方法的第一行,根據handler和mehthod建立HandlerMethod對象。第二行經過handlerMethods map來獲取當前mapping對應的HandlerMethod。而後判斷是否存在相同的RequestMapping配置。以下這種配置就會致使此處拋
    Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map...
    異常
@Controller
@RequestMapping("/AmbiguousTest")
public class AmbiguousTestController {
    @RequestMapping(value = "/test1")
    @ResponseBody
    public String test1(){
        return "method test1";
    }

    @RequestMapping(value = "/test1")
    @ResponseBody
    public String test2(){
        return "method test2";
    }
}
  • 在SpingMVC啓動(初始化)階段檢查RequestMapping配置是否有歧義,這是其中一處檢查歧義的(後面還會提到一個在運行時檢查歧義性的地方)。而後確認配置正常之後會把該RequestMappingInfo和HandlerMethod對象添加至handlerMethods(LinkedHashMap<RequestMappingInfo,HandlerMethod>)中,靜接着把RequestMapping註解的value和ReuqestMappingInfo對象添加至urlMap中。
registerHandlerMethod方法簡單總結

該方法的主要有3個職責html

  1. 檢查RequestMapping註解配置是否有歧義。
  2. 構建RequestMappingInfo到HandlerMethod的映射map。該map即是AbstractHandlerMethodMapping的成員變量handlerMethods。LinkedHashMap<RequestMappingInfo,HandlerMethod>。
  3. 構建AbstractHandlerMethodMapping的成員變量urlMap,MultiValueMap<String,RequestMappingInfo>。這個數據結構能夠把它理解成Map<String,List >。其中String類型的key存放的是處理方法上RequestMapping註解的value。就是具體的uri
    先有以下Controller
@Controller
@RequestMapping("/UrlMap")
public class UrlMapController {

    @RequestMapping(value = "/test1", method = RequestMethod.GET)
    @ResponseBody
    public String test1(){
        return "method test1";
    }

    @RequestMapping(value = "/test1")
    @ResponseBody
    public String test2(){
        return "method test2";
    }

    @RequestMapping(value = "/test3")
    @ResponseBody
    public String test3(){
        return "method test3";
    }
}
  • 初始化完成後,對應AbstractHandlerMethodMapping的urlMap的結構以下
  • 以上即是SpringMVC初始化的主要過程java

    查找過程

  • 爲了理解查找流程,帶着一個問題來看,現有以下Controller
@Controller
@RequestMapping("/LookupTest")
public class LookupTestController {

    @RequestMapping(value = "/test1", method = RequestMethod.GET)
    @ResponseBody
    public String test1(){
        return "method test1";
    }

    @RequestMapping(value = "/test1", headers = "Referer=https://www.baidu.com")
    @ResponseBody
    public String test2(){
        return "method test2";
    }

    @RequestMapping(value = "/test1", params = "id=1")
    @ResponseBody
    public String test3(){
        return "method test3";
    }

    @RequestMapping(value = "/*")
    @ResponseBody
    public String test4(){
        return "method test4";
    }
}
  • 有以下請求
  • 這個請求會進入哪個方法?
  • web容器(Tomcat、jetty)接收請求後,交給DispatcherServlet處理。FrameworkServlet調用對應請求方法(eg:get調用doGet),而後調用processRequest方法。進入processRequest方法後,一系列處理後,在line:936進入doService方法。而後在Line856進入doDispatch方法。在line:896獲取當前請求的處理器handler。而後進入AbstractHandlerMethodMapping的lookupHandlerMethod方法。代碼以下
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
  List<Match> matches = new ArrayList<Match>();
   //根據uri獲取直接匹配的RequestMappingInfos
  List<T> directPathMatches = this.urlMap.get(lookupPath);
  if (directPathMatches != null) {
      addMatchingMappings(directPathMatches, matches, request);
  }
  //不存在直接匹配的RequetMappingInfo,遍歷全部RequestMappingInfo
  if (matches.isEmpty()) {
      // No choice but to go through all mappings
      addMatchingMappings(this.handlerMethods.keySet(), matches, request);
  }
   //獲取最佳匹配的RequestMappingInfo對應的HandlerMethod
  if (!matches.isEmpty()) {
      Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
      Collections.sort(matches, comparator);

      if (logger.isTraceEnabled()) {
        logger.trace("Found " + matches.size() + " matching mapping(s) for [" + lookupPath + "] : " + matches);
      }
      //再一次檢查配置的歧義性
      Match bestMatch = matches.get(0);
      if (matches.size() > 1) {
        Match secondBestMatch = matches.get(1);
        if (comparator.compare(bestMatch, secondBestMatch) == 0) {
            Method m1 = bestMatch.handlerMethod.getMethod();
            Method m2 = secondBestMatch.handlerMethod.getMethod();
            throw new IllegalStateException(
                  "Ambiguous handler methods mapped for HTTP path '" + request.getRequestURL() + "': {" +
                  m1 + ", " + m2 + "}");
        }
      }

      handleMatch(bestMatch.mapping, lookupPath, request);
      return bestMatch.handlerMethod;
  }
  else {
      return handleNoMatch(handlerMethods.keySet(), lookupPath, request);
  }
}
  • 進入lookupHandlerMethod方法,其中lookupPath="/LookupTest/test1",根據lookupPath,也就是請求的uri。直接查找urlMap,獲取直接匹配的RequestMappingInfo list。這裏會匹配到3個RequestMappingInfo。以下
    git

  • 而後進入addMatchingMappings方法
private void addMatchingMappings(Collection<T> mappings, List<Match> matches, HttpServletRequest request) {
  for (T mapping : mappings) {
      T match = getMatchingMapping(mapping, request);
      if (match != null) {
        matches.add(new Match(match, handlerMethods.get(mapping)));
      }
  }
}
  • 這個方法的職責是遍歷當前請求的uri和mappings中的RequestMappingInfo可否匹配上,若是能匹配上,建立一個相同的RequestMappingInfo對象。再獲取RequestMappingInfo對應的handlerMethod。而後建立一個Match對象添加至matches list中。執行完addMatchingMappings方法,回到lookupHandlerMethod。這時候matches還有3個能匹配上的RequestMappingInfo對象。接下來的處理即是對matchers列表進行排序,而後獲取列表的第一個元素做爲最佳匹配。返回Match的HandlerMethod。這裏進入RequestMappingInfo的compareTo方法,看一下具體的排序邏輯。代碼以下
public int compareTo(RequestMappingInfo other, HttpServletRequest request) {
  int result = patternsCondition.compareTo(other.getPatternsCondition(), request);
  if (result != 0) {
      return result;
  }
  result = paramsCondition.compareTo(other.getParamsCondition(), request);
  if (result != 0) {
      return result;
  }
  result = headersCondition.compareTo(other.getHeadersCondition(), request);
  if (result != 0) {
      return result;
  }
  result = consumesCondition.compareTo(other.getConsumesCondition(), request);
  if (result != 0) {
      return result;
  }
  result = producesCondition.compareTo(other.getProducesCondition(), request);
  if (result != 0) {
      return result;
  }
  result = methodsCondition.compareTo(other.getMethodsCondition(), request);
  if (result != 0) {
      return result;
  }
  result = customConditionHolder.compareTo(other.customConditionHolder, request);
  if (result != 0) {
      return result;
  }
  return 0;
}
  • 代碼裏能夠看出,匹配的前後順序是value>params>headers>consumes>produces>methods>custom,看到這裏,前面的問題就能輕易得出答案了。在value相同的狀況,params更能先匹配。因此那個請求會進入test3()方法。再回到lookupHandlerMethod,在找到HandlerMethod。SpringMVC還會這裏再一次檢查配置的歧義性,這裏檢查的原理是經過比較匹配度最高的兩個RequestMappingInfo進行比較。此處可能會有疑問在初始化SpringMVC有檢查配置的歧義性,這裏爲何還會檢查一次。假如如今Controller中有以下兩個方法,如下配置是能經過初始化歧義性檢查的。
@RequestMapping(value = "/test5", method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String test5(){
    return "method test5";
}
@RequestMapping(value = "/test5", method = {RequestMethod.GET, RequestMethod.DELETE})
@ResponseBody
public String test6(){
    return "method test6";
}
  • 如今執行 http://localhost:8080/SpringMVC-Demo/LookupTest/test5 請求,便會在lookupHandlerMethod方法中拋
    java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path 'http://localhost:8080/SpringMVC-Demo/LookupTest/test5'異常。這裏拋該異常是由於RequestMethodsRequestCondition的compareTo方法是比較的method數。代碼以下
public int compareTo(RequestMethodsRequestCondition other, HttpServletRequest request) {
  return other.methods.size() - this.methods.size();
}
  • 何時匹配通配符?當經過urlMap獲取不到直接匹配value的RequestMappingInfo時纔會走通配符匹配進入addMatchingMappings方法。

總結

  • 解析所使用代碼已上傳至github,https://github.com/wycm/SpringMVC-Demo
  • 以上源碼是基於SpringMVC 3.2.2.RELEASE版本。以上即是SpringMVC請求查找的主要過程,但願對你們有幫助。本文可能有錯誤,但願讀者可以指出來。

版權聲明
做者:wycm
出處:https://www.cnblogs.com/w-y-c-m/p/8416630.html
您的支持是對博主最大的鼓勵,感謝您的認真閱讀。
本文版權歸做者全部,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然保留追究法律責任的權利。
一個程序員平常分享,包括但不限於爬蟲、Java後端技術,歡迎關注程序員

相關文章
相關標籤/搜索