什么是 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源代码分析》

 

posted @ 2021-07-03 23:44  秋风扫落木  阅读(5493)  评论(0编辑  收藏  举报
我的页脚