之前的文章里,介绍了DispatcherSerlvet处理请求的流程。

其中一个核心的步骤是:请求地址映射,即根据request获取对应的HandlerExcecutionChain

为了后续的请求地址映射,在项目初始化时,需要先将request-handler映射关系缓存起来。

HandlerMapping有很多实现类,比如RequestMappingHandlerMappingBeanNameUrlHandlerMappingRouterFunctionMapping,它们分别对应不同的Controller接口定义规则。

这篇文章要介绍的是RequestMappingHandlerMapping请求地址映射的初始化流程。

大家看到RequestMappingHandlerMapping可能会感到陌生。

实际上,它是我们日常打交道最多的HandlerMapping实现类:它是@Controller@RequestMapping的底层实现。

RequestMappingHanlderMapping初始化时,会根据@Controller@RequestMapping创建RequestMappingInfo,将request-handler映射关系缓存起来。

首先,我们简单来看一下RequestMappingHandlerMapping的类图:

RequestMappingHandlerMapping实现了InitializingBean接口。

在Spring容器设置完所有bean的属性,以及执行完XxxAware接口的setXxx()方法后,会触发InitializingBeanafterPropertiesSet()方法。

AbstractHandlerMethodMappingafterPropertiesSet()方法中,会完成请求地址映射的初始化流程:

public void afterPropertiesSet() {
initHandlerMethods();
}

AbstractHandlerMethodMappinginitHandlerMethods方法中,会遍历容器中所有bean进行处理:

protected void initHandlerMethods() {
// 1、遍历所有bean的名称
for (String beanName : getCandidateBeanNames()) {
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
// 2、解析bean
processCandidateBean(beanName);
}
}
handlerMethodsInitialized(getHandlerMethods());
}

AbstractHandlerMethodMappingprocessCandidateBean方法中,会对bean进行筛选。如果该bean的类对象中包含@ControllerRequestMapping注解,会进一步遍历该类对象的各个方法:

protected void processCandidateBean(String beanName) {
Class<?> beanType = null;
try {
beanType = obtainApplicationContext().getType(beanName);
}
catch (Throwable ex) {
// An unresolvable bean type, probably from a lazy bean - let's ignore it.
if (logger.isTraceEnabled()) {
logger.trace("Could not resolve type for bean '" + beanName + "'", ex);
}
}
// 1、判断bean的类对象是否包含@Controller或@RequestMapping
if (beanType != null && isHandler(beanType)) {
// 2、构造request-handler映射信息
detectHandlerMethods(beanName);
}
}

RequestMappingHandlerMappingisHandler()方法中,会判断当前类对象是否包含@Controller@RequestMapping注解:

protected boolean isHandler(Class<?> beanType) {
return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
}

AbstractHandlerMethodMappingdetectHandlerMethods方法中,会构造并缓存request-handler信息:

protected void detectHandlerMethods(Object handler) {
Class<?> handlerType = (handler instanceof String ?
obtainApplicationContext().getType((String) handler) : handler.getClass()); if (handlerType != null) {
Class<?> userType = ClassUtils.getUserClass(handlerType);
// 1、遍历类对象的各个方法,返回Method-RequestMappingInfo映射
Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
(MethodIntrospector.MetadataLookup<T>) method -> {
try {
// 2、构造request-handler请求地址映射
return getMappingForMethod(method, userType);
}
catch (Throwable ex) {
throw new IllegalStateException("Invalid mapping on handler class [" +
userType.getName() + "]: " + method, ex);
}
});
if (logger.isTraceEnabled()) {
logger.trace(formatMappings(userType, methods));
}
else if (mappingsLogger.isDebugEnabled()) {
mappingsLogger.debug(formatMappings(userType, methods));
}
// 3、缓存request-handler请求地址映射
methods.forEach((method, mapping) -> {
Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
registerHandlerMethod(handler, invocableMethod, mapping);
});
}
}

MethodIntrospectorselectMethods()方法中,会遍历类对象各个方法,调用RequestMappingHandlerMappinggetMappingForMethod()方法,构造request地址信息:

  • 如果该方法满足书写规则,即含有@RequestMapping,会返回RequestMappingInfo对象
  • 如果该方法不满足书写规则,会返回null

MethodIntrospectorselectMethods()方法会将所有request地址信息不为nullMethod-RequestMappingInfo映射返回。

RequestMappingHandlerMappinggetMappingForMethod()方法中,会构造完整的request地址信息。主要包括以下步骤:

  1. 构造方法级别的request地址信息
  2. 构造类级别的request地址信息
  3. 整合两个级别的request地址信息,构造出完整的request地址信息

RequestMappingHandlerMappinggetMappingForMethod()方法源码如下:

protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
// 1、构造方法级别的request-handler信息
RequestMappingInfo info = createRequestMappingInfo(method);
if (info != null) {
// 2、构造类级别的request-handler信息
RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
if (typeInfo != null) {
// 3、整合两个级别的request-handler信息,构造出完整的request-handler信息
info = typeInfo.combine(info);
}
String prefix = getPathPrefix(handlerType);
if (prefix != null) {
info = RequestMappingInfo.paths(prefix).options(this.config).build().combine(info);
}
}
return info;
}

构造request地址信息很简单,只是从@RequestMapping注解中获取各个属性,创建RequestMappingInfo(在实际请求地址映射时,会对所有属性进行校验):

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

在整合request地址信息过程中,会分别调用各个属性的整合规则进行整合:

public RequestMappingInfo combine(RequestMappingInfo other) {
String name = combineNames(other); PathPatternsRequestCondition pathPatterns =
(this.pathPatternsCondition != null && other.pathPatternsCondition != null ?
this.pathPatternsCondition.combine(other.pathPatternsCondition) : null); PatternsRequestCondition patterns =
(this.patternsCondition != null && other.patternsCondition != null ?
this.patternsCondition.combine(other.patternsCondition) : null); RequestMethodsRequestCondition methods = this.methodsCondition.combine(other.methodsCondition);
ParamsRequestCondition params = this.paramsCondition.combine(other.paramsCondition);
HeadersRequestCondition headers = this.headersCondition.combine(other.headersCondition);
ConsumesRequestCondition consumes = this.consumesCondition.combine(other.consumesCondition);
ProducesRequestCondition produces = this.producesCondition.combine(other.producesCondition);
RequestConditionHolder custom = this.customConditionHolder.combine(other.customConditionHolder); return new RequestMappingInfo(name, pathPatterns, patterns,
methods, params, headers, consumes, produces, custom, this.options);
}

不同的属性有不同的整合规则,比如对于methodsparamsheaders会取并集,而对于consumesproduces方法级别优先。

介绍完request地址信息的构造过程,我们回到AbstractHandlerMethodMappingdetectHandlerMethods方法中。此时,我们得到了Method-RequestMappingInfo映射信息。

接下来,会遍历这个映射,筛选出实际可执行的方法(即非私有的、非静态的和非超类的)。

最终,将可执行的方法对应的request-handler信息缓存起来。核心代码位于AbstractHandlerMethodMapping.MappingRegistry内部类的register()方法:

public void register(T mapping, Object handler, Method method) {
this.readWriteLock.writeLock().lock();
try {
// 1、创建HandlerMethod对象,即handler
HandlerMethod handlerMethod = createHandlerMethod(handler, method);
// 2、校验该request地址信息是否已经存在
validateMethodMapping(handlerMethod, mapping);
// 3、缓存path-RequestMappingInfo映射
Set<String> directPaths = AbstractHandlerMethodMapping.this.getDirectPaths(mapping);
for (String path : directPaths) {
this.pathLookup.add(path, mapping);
}
// 4、缓存name-RequestMappingInfo映射
String name = null;
if (getNamingStrategy() != null) {
name = getNamingStrategy().getName(handlerMethod, mapping);
addMappingName(name, handlerMethod);
}
// 5、缓存CORS配置信息
CorsConfiguration corsConfig = initCorsConfiguration(handler, method, mapping);
if (corsConfig != null) {
corsConfig.validateAllowCredentials();
this.corsLookup.put(handlerMethod, corsConfig);
}
// 6、缓存RequestMappingInfo-MappingRegistration信息
this.registry.put(mapping,
new MappingRegistration<>(mapping, handlerMethod, directPaths, name, corsConfig != null));
}
finally {
this.readWriteLock.writeLock().unlock();
}
}

需要注意的是,在这个过程中还会缓存跨域配置信息,主要是@CrossOrigin注解方式的跨域配置信息。

RequestMappingHandlerMappinginitCorsConfiguration()方法中,会获取类级别和方法级别的@CrossOrigin信息,构造出完整的跨域配置信息:

protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
HandlerMethod handlerMethod = createHandlerMethod(handler, method);
Class<?> beanType = handlerMethod.getBeanType();
// 1、获取类级别的@CrossOrigin信息
CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(beanType, CrossOrigin.class);
// 2、获取方法级别的@CrossOrigin信息
CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class); if (typeAnnotation == null && methodAnnotation == null) {
return null;
}
// 3、整合两个级别的@CrossOrigin信息
CorsConfiguration config = new CorsConfiguration();
updateCorsConfig(config, typeAnnotation);
updateCorsConfig(config, methodAnnotation); if (CollectionUtils.isEmpty(config.getAllowedMethods())) {
for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) {
config.addAllowedMethod(allowedMethod.name());
}
}
return config.applyPermitDefaultValues();
}

在整合@CrossOrigin信息过程中,有三种情况:

  1. 对于originsoriginPatternsallowedHeadersexposedHeadersmethods等列表属性,会获取全部。
  2. 对于allowCredentials,会优先获取方法级别的配置。
  3. 对于maxAge,会获取最大值。

至此,我们走完了RequestMappingHandlerMapping中请求地址映射的初始化流程。最后总结一下流程如下:

  1. 遍历容器中所有bean对象
  2. 如果bean的类对象含有@Controller@RequestMapping注解,进行下一步
  3. 遍历bean的类对象的所有方法,根据方法的@RequestMapping注解,构造RequestMappingInfo对象
  4. 遍历Method-RequestMappingInfo映射,过滤出可执行方法
  5. 缓存各种request-handler映射信息,同时会缓存@CrossOrigin的跨域配置信息

此时,我们可以充分理解到,request-handler请求地址映射信息中requesthandler的含义:

  • request:主要是@RequestMapping中含有的各个属性的信息
  • handler:标注@RequestMapping的方法

RequestMappingHandlerMapping请求地址映射的初始化流程!的更多相关文章

  1. SpringMVC源码剖析(三)- DispatcherServlet的初始化流程

    在我们第一次学Servlet编程,学Java Web的时候,还没有那么多框架.我们开发一个简单的功能要做的事情很简单,就是继承HttpServlet,根据需要重写一下doGet,doPost方法,跳转 ...

  2. ASP.NET初始化流程分析2

    上一篇讲了从创建应用程序域到创建ISAPIRuntime实例的过程,本篇继续讲Asp.net处理第一次请求的必要的初始化过程. ISAPIRuntime分析 ISAPIRuntime在System.W ...

  3. Shiro权限管理框架(三):Shiro中权限过滤器的初始化流程和实现原理

    本篇是Shiro系列第三篇,Shiro中的过滤器初始化流程和实现原理.Shiro基于URL的权限控制是通过Filter实现的,本篇从我们注入的ShiroFilterFactoryBean开始入手,翻看 ...

  4. 痞子衡嵌入式:深入i.MXRT1050系列ROM中串行NOR Flash启动初始化流程

    大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家分享的是深入i.MXRT1050系列ROM中串行NOR Flash启动初始化流程. 从外部串行NOR Flash启动问题是i.MXRT系列开发最 ...

  5. 【技术博客】Flutter—使用网络请求的页面搭建流程、State生命周期、一些组件的应用

    Flutter-使用网络请求的页面搭建流程.State生命周期.一些组件的应用 使用网络请求的页面搭建流程 ​ 在开发APP时,我们常常会遇到如下场景:进入一个页面后,要先进行网络调用,然后使用调用返 ...

  6. Sentinel-Go 源码系列(二)|初始化流程和责任链设计模式

    上节中我们知道了 Sentinel-Go 大概能做什么事情,最简单的例子如何跑起来 其实我早就写好了本系列的第二篇,但迟迟没有发布,感觉光初始化流程显得有些单一,于是又补充了责任链模式,二合一,内容显 ...

  7. Spring框架系列(7) - Spring IOC实现原理详解之IOC初始化流程

    上文,我们看了IOC设计要点和设计结构:紧接着这篇,我们可以看下源码的实现了:Spring如何实现将资源配置(以xml配置为例)通过加载,解析,生成BeanDefination并注册到IoC容器中的. ...

  8. spring自动扫描、DispatcherServlet初始化流程、spring控制器Controller 过程剖析

    spring自动扫描1.自动扫描解析器ComponentScanBeanDefinitionParser,从doScan开始扫描解析指定包路径下的类注解信息并注册到工厂容器中. 2.进入后findCa ...

  9. 【开源】OSharp3.3框架解说系列(7.1):初始化流程概述

    OSharp是什么? OSharp是个快速开发框架,但不是一个大而全的包罗万象的框架,严格的说,OSharp中什么都没有实现.与其他大而全的框架最大的不同点,就是OSharp只做抽象封装,不做实现.依 ...

  10. u-boot中nandflash初始化流程分析(转)

    u-boot中nandflash初始化流程分析(转) 原文地址http://zhuairlunjj.blog.163.com/blog/static/80050945201092011249136/ ...

随机推荐

  1. 2. Fluentd事件的生命周期

    事件(Event)是Fluentd内部处理流程使用的数据结构,日志记录一旦进入Fluentd便被封装成一个event.Event由三部分组成:tag.time.record. tag: 标识事件的来源 ...

  2. img和div之间有间隙的原因及解决方法

    div 中 存在 img标签,由于img标签的 display:inline-block 属性. #####display:inline-block布局的元素在chrome下会出现几像素的间隙,原因是 ...

  3. vue2.x引入threejs

    @ 目录 vue2.x引入threejs npm安装 使用指定版本: 其他插件 实例 强调 vue2.x引入threejs npm安装 npm install three 使用指定版本: npm in ...

  4. 改善C#程序的方法-2 使用TryParse

    一 使用TryParse,而不是Parse 除string外的所有基元类型,都有两个将string类型转型为其本身类型的方法:Parse 和 TryParse. 以double类型为例,这两个方法最简 ...

  5. 引擎之旅 Chapter.4 日志系统

    关于近段时间为何没有更新的解释:Find a new job. 目录 引言 日志语句的分类 控制台窗体 和 VSOutput Tab的日志打印 存储至特定的文件中 展示堆栈信息 引言 一般来说,一个优 ...

  6. P7800 [COCI2015-2016#6] PAROVI 方法记录

    原题链接 桔梗花于此开放 [COCI2015-2016#6] PAROVI 题目描述 \(\text{Mirko}\) 和 \(\text{Slavko}\) 在玩一个游戏,先由 \(\text{Mi ...

  7. 华为路由器DHCP配置基本命令

    配置基于接口地址池DHCP (动态主机配置协议) [R1]dhcp enable 路由器上开启DHCP [R1]int g0/0/0 [R1-GigabitEthernet0/0/0]dhcp sel ...

  8. Hyperf 接入阿里云ACM应用配置管理中心

    参考: 阿里云文档:https://help.aliyun.com/document_detail/85466.html?spm=a2c4g.11186623.6.550.43cb42d4Af4Tu0 ...

  9. dubbo的一系列配置与搭建

    dubbo新的版本采用前后端分离技术,在github上下载的时候,不仅仅只是一个dubbo-admin 而是将admin包分离为dubbo-admin-ui前端包和dubbo-admin-server ...

  10. Day06:运算符详解

    运算符 算术运算符:+,-,*,/,%(取余:也叫模运算),++(自增),--(自减)........... 二次运算符+,-,*,/ int a=10; int b=20; int c=50; in ...