承接前文SpringMVC源码情操陶冶-AbstractHandlerMapping,本文将介绍如何注册HandlerMethod对象作为handler

类结构瞧一瞧

public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMapping implements InitializingBean{}

此为抽象方法,并实现了initializingBean接口,其实主要的注册操作则是通过afterPropertiesSet()接口方法来调用的

AbstractHandlerMethodMapping#afterPropertiesSet()-初始化HandlerMethod对象

源码奉上

	@Override
public void afterPropertiesSet() {
initHandlerMethods();
}

转而看initHandlerMethods(),观察是如何实现加载HandlerMethod


protected void initHandlerMethods() {
//获取springmvc上下文的所有注册的bean
String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
getApplicationContext().getBeanNamesForType(Object.class)); for (String beanName : beanNames) {
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
Class<?> beanType = null;
try {
beanType = getApplicationContext().getType(beanName);
}
catch (Throwable ex) {
// An unresolvable bean type, probably from a lazy bean - let's ignore it.
if (logger.isDebugEnabled()) {
logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
}
}
//isHandler()是抽象方法,主要供子类需要扫描什么类型的bean
if (beanType != null && isHandler(beanType)) {
//解析其中的HandlerMethod进行注册
detectHandlerMethods(beanName);
}
}
}
//抽象方法,目前尚无实现
handlerMethodsInitialized(getHandlerMethods());
}

接下来稍微分析springmvc是如何解析bean并获取其中的HandlerMethod

AbstractHandlerMethodMapping#detectHandlerMethods()解析

源码奉上

	protected void detectHandlerMethods(final Object handler) {
Class<?> handlerType = (handler instanceof String ?
getApplicationContext().getType((String) handler) : handler.getClass());
//因为有些是CGLIB代理生成的,获取真实的类
final Class<?> userType = ClassUtils.getUserClass(handlerType); Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
new MethodIntrospector.MetadataLookup<T>() {
@Override
public T inspect(Method method) {
try {
//模板方法获取handlerMethod的mapping属性
return getMappingForMethod(method, userType);
}
catch (Throwable ex) {
throw new IllegalStateException("Invalid mapping on handler class [" +
userType.getName() + "]: " + method, ex);
}
}
}); //对查找到的HandlerMethod进行注册,保存至内部类mappingRegistry对象中
for (Map.Entry<Method, T> entry : methods.entrySet()) {
//作下判断,method是否从属于userType
Method invocableMethod = AopUtils.selectInvocableMethod(entry.getKey(), userType);
T mapping = entry.getValue();
registerHandlerMethod(handler, invocableMethod, mapping);
}
}

针对唯一的实现类RequestMappingHandlerMapping,上述的mapping属性指代的是RequestMappingInfo对象,内部包含@RequestMapping注解的内部属性,比如methodparamsconsumesproducesvalue以及对应的属性判断类

RequestMappingHandlerMapping-唯一实现类

作为HandlerMethod对象的配置者,我们主要观察其复写的几个方法

RequestMappingHandlerMapping#afterPropertiesSet()

代码奉上

	@Override
public void afterPropertiesSet() {
//config为RequestMappingInfo的创建对象
this.config = new RequestMappingInfo.BuilderConfiguration();
//设置urlPathHelper默认为UrlPathHelper.class
this.config.setUrlPathHelper(getUrlPathHelper());
//默认为AntPathMatcher,路径匹配校验器
this.config.setPathMatcher(getPathMatcher());
//是否支持后缀补充,默认为true
this.config.setSuffixPatternMatch(this.useSuffixPatternMatch);
//是否添加"/"后缀,默认为true
this.config.setTrailingSlashMatch(this.useTrailingSlashMatch);
//是否采用mediaType匹配模式,比如.json/.xml模式的匹配,默认为false
this.config.setRegisteredSuffixPatternMatch(this.useRegisteredSuffixPatternMatch);
//mediaType处理类
this.config.setContentNegotiationManager(getContentNegotiationManager());
//调用父类进行HandlerMethod的注册工作
super.afterPropertiesSet();
}

此处如何设置可通过查看博文>>>SpringMVC源码情操陶冶-AnnotationDrivenBeanDefinitionParser注解解析器

RequestMappingHandlerMapping#isHandler()-判断获取何种类型的Handler

获取@Controller/@RequestMapping注解下的handler

	@Override
protected boolean isHandler(Class<?> beanType) {
//优先匹配@Controller
return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
}

RequestMappingHandlerMapping#getMappingForMethod()-获取HandlerMethod对应的mapping属性

此处指的是RequestMappingInfo,主要包含了路径匹配策略、@RequestMapping属性匹配策略,简单源码奉上

	@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
//对method以及class类都进行创建RequestMappingInfo
//因为@RequestMapping可以在方法上/类上应用注解
RequestMappingInfo info = createRequestMappingInfo(method);
if (info != null) {
RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
if (typeInfo != null) {
info = typeInfo.combine(info);
}
}
return info;
}

由代码可知,其将拼装Class上的@RequestMapping和Method上的@RequestMapping组装成RequestMappingInfo对象,其内部的属性读者有兴趣可自行去分析。

此处对createRequestMappingInfo()方法作下补充

	protected RequestMappingInfo createRequestMappingInfo(
RequestMapping requestMapping, RequestCondition<?> customCondition) { return RequestMappingInfo
.paths(resolveEmbeddedValuesInPatterns(requestMapping.path()))
.methods(requestMapping.method())
.params(requestMapping.params())
.headers(requestMapping.headers())
.consumes(requestMapping.consumes())
.produces(requestMapping.produces())
.mappingName(requestMapping.name())
.customCondition(customCondition)
.options(this.config)
.build();
}

小结

  • 介绍AbstractHandlerMethodMapping如何创建HandlerMethod,调用者为RequestMappingHandlerMapping,其可通过mvc:annotation-driven注册,具体可查看>>>SpringMVC源码情操陶冶-AnnotationDrivenBeanDefinitionParser注解解析器

  • 其中其唯一实现类RequestMappingHandlerMapping主要是获取@Controller下的@RequestMapping注解的方法将其注册为HandlerMethod对象,其余的相关信息则注册为RequestMappingInfo对象供对路径信息匹配

  • 其中如何获取HandlerMethod查看前言中的链接即可

SpringMVC源码情操陶冶-AbstractHandlerMethodMapping的更多相关文章

  1. SpringMVC源码情操陶冶-AnnotationDrivenBeanDefinitionParser注解解析器

    mvc:annotation-driven节点的解析器,是springmvc的核心解析器 官方注释 Open Declaration org.springframework.web.servlet.c ...

  2. SpringMVC源码情操陶冶-FreeMarker之web配置

    前言:本文不讲解FreeMarkerView视图的相关配置,其配置基本由FreeMarkerViewResolver实现,具体可参考>>>SpringMVC源码情操陶冶-ViewRe ...

  3. SpringMVC源码情操陶冶-DispatcherServlet

    本文对springmvc核心类DispatcherServlet作下简单的向导,方便博主与读者查阅 DispatcherServlet-继承关系 分析DispatcherServlet的继承关系以及主 ...

  4. SpringMVC源码情操陶冶-DispatcherServlet父类简析

    阅读源码有助于陶冶情操,本文对springmvc作个简单的向导 springmvc-web.xml配置 <servlet> <servlet-name>dispatch< ...

  5. SpringMVC源码情操陶冶-DispatcherServlet类简析(一)

    阅读源码有利于陶冶情操,此文承接前文SpringMVC源码情操陶冶-DispatcherServlet父类简析 注意:springmvc初始化其他内容,其对应的配置文件已被加载至beanFactory ...

  6. SpringMVC源码情操陶冶-DispatcherServlet简析(二)

    承接前文SpringMVC源码情操陶冶-DispatcherServlet类简析(一),主要讲述初始化的操作,本文将简单介绍springmvc如何处理请求 DispatcherServlet#doDi ...

  7. SpringMVC源码情操陶冶-HandlerAdapter适配器简析

    springmvc中对业务的具体处理是通过HandlerAdapter适配器操作的 HandlerAdapter接口方法 列表如下 /** * Given a handler instance, re ...

  8. SpringMVC源码情操陶冶-AbstractUrlHandlerMapping

    承接前文SpringMVC源码情操陶冶-AbstractHandlerMapping,前文主要讲解了如何获取handler处理对象,本文将针对beanName注册为handler对象作下解析 Abst ...

  9. SpringMVC源码情操陶冶-RequestMappingHandlerAdapter适配器

    承接前文SpringMVC源码情操陶冶-HandlerAdapter适配器简析.RequestMappingHandlerAdapter适配器组件是专门处理RequestMappingHandlerM ...

随机推荐

  1. 51 Nod 1005 大数加法【Java大数乱搞,python大数乱搞】

    1005 大数加法 基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 给出2个大整数A,B,计算A+B的结果. Input 第1行:大数A 第2行:大数B (A,B的长度  ...

  2. [hdu5225][BC#40]Tom and permutation

    好久没写题解了..GDKOI被数位DP教做人了一发,现在终于来填数位DP的大坑了>_<. 发现自己以前写的关于数位DP的东西...因为没结合图形+语文水平拙计现在已经完全看不懂了嗯. 看来 ...

  3. POJ3041-Asteroids-匈牙利算法

    Asteroids Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 23963   Accepted: 12989 Descr ...

  4. js实现深拷贝和浅拷贝

    浅拷贝: 思路----------把父对象的属性,全部拷贝给子对象,实现继承. 问题---------如果父对象的属性等于数组或另一个对象,那么实际上,子对象获得的只是一个内存地址,不会开辟新栈,不是 ...

  5. HDU 2063 过山车(模板—— 二分图最大匹配问题)

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2063  解题思路: 二分图最大匹配模板题. AC代码: #include<stdio.h> ...

  6. JS URI Encode

    javascript中存在几种对URL字符串进行编码的方法:escape/encodeURI/encodeURIComponent.这几种编码所起的作用各不相同. escape 采用ISO Latin ...

  7. 性能测试资源监控工具nmon使用方法

    1.简述  nmon是一种在AIX与各种Linux操作系统上广泛使用的监控与分析工具,相对于其它一些系统资源监控工具来说,nmon所记录的信息是比较全面的,它能在系统运行过程中实时地捕捉系统资源的使用 ...

  8. JXLS使用方法(文件上传读取)xlsx文件读取

    1.官方文档:http://jxls.sourceforge.net/reference/reader.html 2.demo git地址:https://bitbucket.org/leonate/ ...

  9. mysql 存在索引但不能使用索引的典型场景

    mysql 演示数据库:http://downloads.mysql.com/docs/sakila-db.zip 以%开头的LIKE查询不能够利用B-tree索引 explain select * ...

  10. 优化 gruop by 语句

    默认情况下,mysql对所有的gruop by col1,col2...的字段进行排序.如果查询包含group by但用户想要避免排序结果的消耗,则可以指定order by null禁止排序. exp ...