什么是 HandlerMethod ?


首先來看文檔注釋:

Encapsulates information about a handler method consisting of a method and a bean. Provides convenient access to method parameters, the method return value, method annotations, etc.
The class may be created with a bean instance or with a bean name (e.g. lazy-init bean, prototype bean). Use createWithResolvedBean() to obtain a HandlerMethod instance with a bean instance resolved through the associated BeanFactory.

翻譯過來大概是這樣:

封裝有關由方法和bean組成的處理程序方法的信息。提供對方法參數、方法返回值、方法注釋等的方便訪問。
可以使用bean實例或bean名稱(例如lazy init bean、prototype bean)創建類。使用createWithResolvedBean()獲取HandlerMethod實例,該實例具有通過關聯的BeanFactory解析的bean實例。

理解HandlerMethod 在spring mvc 處理請求過程中的作用

SpringMVC 應用啟動時會搜集並分析每個Web控制器方法,從中提取對應的 "<請求匹配條件,控制器方法>“ 映射關系,形成一個映射關系表保存在一個RequestMappingHandlerMapping bean中。然后在客戶請求到達時,再使用 RequestMappingHandlerMapping 中的該映射關系表找到相應的控制器方法去處理該請求。在RequestMappingHandlerMapping 中保存的每個 ”<請求匹配條件,控制器方法>" 映射關系對兒中, "請求匹配條件" 通過 RequestMappingInfo 包裝和表示,而 "控制器方法"則通過 HandlerMethod 來包裝和表示。

一個HandlerMethod對象,可以認為是對如下信息的一個包裝 :

 
信息名稱 介紹
Object bean Web控制器方法所在的Web控制器 bean。可以是字符串,代表 bean 的名稱; 也可以是 bean 實例對象本身。
Class beanType Web控制器方法所在的Web控制器bean 的類型, 如果該bean被代理,這里記錄的是被代理的用戶類信息
Method method Web控制器方法
Method bridgedMethod 被橋接的Web控制器方法
MethodParameter[] parameters Web控制器方法的參數信息: 所在類所在方法,參數,索引,參數類型
HttpStatus responseStatus 注解@ResponseStatuscode屬性
String responseStatusReason

注解@ResponseStatusreason屬性

 

 

 

 

 

 

 

 

 

 

 

HandlerMethod最主要的使用位置如下 :

1 RequestMappingHandlerMapping#afterPropertiesSet
2 RequestMappingHandlerMapping#initHandlerMethods
3 AbstractHandlerMethodMapping#detectHandlerMethods
4 AbstractHandlerMethodMapping#registerHandlerMethod
5 AbstractHandlerMethodMapping$MappingRegistry#register
6 AbstractHandlerMethodMapping#createHandlerMethod

注意AbstractHandlerMethodMappingRequestMappingHandlerMapping的基類。

AbstractHandlerMethodMapping#createHandlerMethod 方法實現如下 :

 1     /**
 2      * Create the HandlerMethod instance.
 3      * @param handler either a bean name or an actual handler instance
 4      * @param method the target method
 5      * @return the created HandlerMethod
 6      */
 7     protected HandlerMethod createHandlerMethod(Object handler, Method method) {
 8         HandlerMethod handlerMethod;
 9         if (handler instanceof String) {
10             // handler 是Web控制器類名稱的情況(通常都是這種情況)
11             String beanName = (String) handler;
12             handlerMethod = new HandlerMethod(beanName,
13                     obtainApplicationContext().getAutowireCapableBeanFactory(), method);
14         }
15         else {
16             // handler 是Web控制器bean實例的情況
17             handlerMethod = new HandlerMethod(handler, method);
18         }
19         return handlerMethod;
20     }

 

參考文獻:

  • 《看透spring mvc源代碼分析》

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM