之前的文章里,介绍了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. golang channel底层结构和实现

    一.介绍 Golang 设计模式: 不要通过共享内存来通信,而要通过通信实现内存共享 channel是基于通信顺序模型(communication sequential processes, CSP) ...

  2. get,post,put,delete四种基础方法对应增删改查

    PUT,DELETE,POST,GET四种基础方法对应增删改查 1.GET请求会向数据库发索取数据的请求,从而来获取信息,该请求就像数据库的select操作一样,只是用来查询一下数据,不会修改.增加数 ...

  3. 作用域通信对象:session用户在登录时通过`void setAttribute(String name,Object value)`方法设置用户名和密码。点击登录按钮后,跳转到另外一个页面显示用户

    作用域通信对象:session session对象基于会话,不同用户拥有不同的会话.同一个用户共享session对象的所有属性.作用域开始客户连接到应用程序的某个页面,结束与服务器断开连接.sessi ...

  4. 表单快速启用城市地区功能 齐博x1齐博x2齐博x3齐博x4齐博x5齐博x6齐博x7齐博x8齐博x9齐博x10

    比如分类系统\application\fenlei\config.php 修改这个文件,里边加入参数 'use_area'=>true, 那么会员中心与后台的,修改发布页面,都会自动加上城市地区 ...

  5. Linux进程间通信(二)

    信号 信号的概念 信号是Linux进程间通信的最古老的一种方式.信号是软件中断,是一种异步通信的方式.信号可以导致一个正在运行的进程被另一个正在运行的异步进程中断,转而处理某个突发事件. 一旦产生信号 ...

  6. ML-L1、L2 正则化

    出现过拟合时,使用正则化可以将模型的拟合程度降低一点点,使曲线变得缓和. L1正则化(LASSO) 正则项是所有参数的绝对值的和.正则化不包含theta0,因为他只是偏置,而不影响曲线的摆动幅度. \ ...

  7. Xpath 高级用法

    xpath 高级用法 1. 匹配当前节点下的所有: .// . 表示当前 // 表示当前标签下的所有标签 注: 要配合使用 2. 匹配某标签的属性值: /@属性名称 这里以input里的value值为 ...

  8. ES6 学习笔记(四)基本类型Number

    1.数值 1.1 .JavaScript数值的特点 不区分整数值和浮点数值. 所有数值均用浮点数值表示. 采用IEEE-754标准定义的64位浮点数格式表示. 整数在实际操作时(如数组索引),则是基于 ...

  9. AK/SK加密认证

    AK/SK认证的实现 AK/SK概述 1.什么是AKSK ak/sk是一种身份认证方式,常用于系统间接口调用时的身份验证,其中ak为Access Key ID,sk为Secret Access Key ...

  10. Codeforces Round #811 (Div. 3)D. Color with Occurrences

    题目大意:给出一个文章t和n个字符串s1,s2...sn: 问能否用这n个字符串将整个文章覆盖: 思路:贪心(最小区间覆盖) 记录每个字符串能够覆盖的所有位置(起点,终点,编号) 排序后贪心的求出是否 ...