Spring MVC : 概念模型 HandlerMethod
Spring MVC
应用启动时会搜集并分析每个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 |
注解@ResponseStatus 的code 属性 |
String responseStatusReason |
注解@ResponseStatus 的reason 属性 |
HandlerMethod
最主要的使用位置:
RequestMappingHandlerMapping#afterPropertiesSet
RequestMappingHandlerMapping#initHandlerMethods
AbstractHandlerMethodMapping#detectHandlerMethods
AbstractHandlerMethodMapping#registerHandlerMethod
AbstractHandlerMethodMapping$MappingRegistry#register
AbstractHandlerMethodMapping#createHandlerMethod
- 1
- 2
- 3
- 4
- 5
- 6
注意 :
AbstractHandlerMethodMapping
是RequestMappingHandlerMapping
的基类。
而AbstractHandlerMethodMapping#createHandlerMethod
方法实现如下 :
/**
* Create the HandlerMethod instance.
* @param handler either a bean name or an actual handler instance
* @param method the target method
* @return the created HandlerMethod
*/
protected HandlerMethod createHandlerMethod(Object handler, Method method) {
HandlerMethod handlerMethod;
if (handler instanceof String) {
// handler 是Web控制器类名称的情况(通常都是这种情况)
String beanName = (String) handler;
handlerMethod = new HandlerMethod(beanName,
obtainApplicationContext().getAutowireCapableBeanFactory(), method);
}
else {
// handler 是Web控制器bean实例的情况
handlerMethod = new HandlerMethod(handler, method);
}
return handlerMethod;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20