当前位置: 首页 > news >正文

spring MVC源码探索之AbstractHandlerMethodMapping

AbstractHandlerMethodMapping 是什么

官方解释是这样的。

/**
 * Abstract base class for {@link HandlerMapping} implementations that define
 * a mapping between a request and a {@link HandlerMethod}.
 *
 * <p>For each registered handler method, a unique mapping is maintained with
 * subclasses defining the details of the mapping type {@code <T>}.
 * @param <T> The mapping for a {@link HandlerMethod} containing the conditions
 * needed to match the handler method to incoming request.
 */
public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMapping implements InitializingBean 

我的理解为AbstractHandlerMethodMapping为每个注册的handler method,对于每个子类映射类型都维护着其唯一的一个映射,就是维护handler method 和URL的关系。主要用于@Controller,@RequestMapping 等注解

AbstractHandlerMethodMapping 实现了InitializingBean接口,InitializingBean是在程序启动的时候执行其唯一的afterPropertiesSet()方法,那我们就先看一下启动时候的要做哪些操作。

initHandlerMethods()

/**
      在初始化的时候发现 handler methods
    * Detects handler methods at initialization.
     */
    @Override
    public void afterPropertiesSet() {
        initHandlerMethods();
    }

在项目启动时会执行initHandlerMethods方法,它的主要功能是扫描应用上下文,发现并注册handler methods。

/**
 * Scan beans in the ApplicationContext, detect and register handler methods.
 * @see #isHandler(Class)
 * @see #getMappingForMethod(Method, Class)
 * @see #handlerMethodsInitialized(Map)
 */
protected void initHandlerMethods() {
        if (logger.isDebugEnabled()) {
                logger.debug("Looking for request mappings in application context: " + getApplicationContext());
        }
        // 获取IOC容器中所有bean
        String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
                        BeanFactoryUtils.beanNamesForTypeIncludingAncestors(obtainApplicationContext(), Object.class) :
                        obtainApplicationContext().getBeanNamesForType(Object.class));

        for (String beanName : beanNames) {
                if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
                        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.isDebugEnabled()) {
                                        logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
                                }
                        }
                        // 判断bean 是否有Controller 注解或者RequestMapping 注解
                        if (beanType != null && isHandler(beanType)) {
                                detectHandlerMethods(beanName);
                        }
                }
        }
        handlerMethodsInitialized(getHandlerMethods());
}

isHandler()

AbstractHandlerMethodMapping#isHandler() RequestMappingHandlerMapping 是目前为止AbstractHandlerMethodMapping的子类中唯一实现了isHandler()方法的子类,看下实现

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

isHandler()方法在这里的作用就是检查beanType是否有@Controller或@RequestMapping注解,这两个注解经常使用,应该都很熟悉了。

detectHandlerMethods()

AbstractHandlerMethodMapping#detectHandlerMethods() 这个方法的作用是从handler中获取handler method并注册

protected void detectHandlerMethods(final Object handler) {
        Class<?> handlerType = (handler instanceof String ?
                        obtainApplicationContext().getType((String) handler) : handler.getClass());

        if (handlerType != null) {
                //为给定的类返回用户定义的类:通常只是给定的类,如果是cglib生成的子类,则返回原始的类。
                final Class<?> userType = ClassUtils.getUserClass(handlerType);
                Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
                                (MethodIntrospector.MetadataLookup<T>) method -> {
                                        try {
                                                // 为处理程序方法提供映射
                                                return getMappingForMethod(method, userType);
                                        }
                                        catch (Throwable ex) {
                                                throw new IllegalStateException("Invalid mapping on handler class [" +
                                                                userType.getName() + "]: " + method, ex);
                                        }
                                });
                if (logger.isDebugEnabled()) {
                        logger.debug(methods.size() + " request handler methods found on " + userType + ": " + methods);
                }

                // 为查找到的handler method 进行注册
                methods.forEach((method, mapping) -> {
                        Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
                        registerHandlerMethod(handler, invocableMethod, mapping);
                });
        }
    }

registerHandlerMethod()

AbstractHandlerMethodMapping#registerHandlerMethod() 的作用是为每个handler method注册它们唯一的映射路径,源码如下:

/**
 * Register a handler method and its unique mapping. Invoked at startup for
 * each detected handler method.
 * @param handler the bean name of the handler or the handler instance
 * @param method the method to register
 * @param mapping the mapping conditions associated with the handler method
 * @throws IllegalStateException if another method was already registered
 * under the same mapping
 */
protected void registerHandlerMethod(Object handler, Method method, T mapping) {
        this.mappingRegistry.register(mapping, handler, method);
}

register方法是AbstractHandlerMethodMapping 内部类MappingRegistry里的方法,MappingRegistry是一个注册表

 

相关文章:

  • Redis线程模型
  • 通过 JFR 与日志深入探索 JVM - 调试 JVM 的工具 WhiteBox API
  • [毕业设计源代码]精品基于SSM的线上点餐系统[包运行成功]
  • C/C++创建tty,创建终端
  • End of line spacing
  • C 长度为0 的数组
  • javaweb JAVA JSP学生信息档案管理系统JSP学生管理系统JSP学生档案管理系统JSP学生信息管理系统
  • 天玑810和天玑900哪个好 天玑810和天玑900差距
  • 如何管理现代信息化机房
  • 单声道D类音频放大器 CS8631E 特点及应用
  • 【Python】第九课 类和对象
  • WPF中加载GIF
  • 快来直播带你了解中国互联网大厂布局元宇宙现状如何?
  • 配置JVM堆栈大小
  • 新美域杂志新美域杂志社新美域编辑部2022年第6期目录
  • 实现windows 窗体的自己画,网上摘抄的,学习了
  • Docker 笔记(2):Dockerfile
  • ECMAScript6(0):ES6简明参考手册
  • JavaScript创建对象的四种方式
  • JavaScript对象详解
  • opencv python Meanshift 和 Camshift
  • React Transition Group -- Transition 组件
  • 观察者模式实现非直接耦合
  • 机器人定位导航技术 激光SLAM与视觉SLAM谁更胜一筹?
  • 通过npm或yarn自动生成vue组件
  • 智能合约开发环境搭建及Hello World合约
  • 终端用户监控:真实用户监控还是模拟监控?
  • 第二十章:异步和文件I/O.(二十三)
  • (1) caustics\
  • (1)Android开发优化---------UI优化
  • (1)虚拟机的安装与使用,linux系统安装
  • (arch)linux 转换文件编码格式
  • (LeetCode) T14. Longest Common Prefix
  • (pt可视化)利用torch的make_grid进行张量可视化
  • (第61天)多租户架构(CDB/PDB)
  • (二)基于wpr_simulation 的Ros机器人运动控制,gazebo仿真
  • (二十五)admin-boot项目之集成消息队列Rabbitmq
  • (附源码)springboot 校园学生兼职系统 毕业设计 742122
  • (简单) HDU 2612 Find a way,BFS。
  • (续)使用Django搭建一个完整的项目(Centos7+Nginx)
  • (已更新)关于Visual Studio 2019安装时VS installer无法下载文件,进度条为0,显示网络有问题的解决办法
  • (原創) 如何讓IE7按第二次Ctrl + Tab時,回到原來的索引標籤? (Web) (IE) (OS) (Windows)...
  • (转)C语言家族扩展收藏 (转)C语言家族扩展
  • .form文件_一篇文章学会文件上传
  • .NET CLR基本术语
  • .NET CORE Aws S3 使用
  • .net 按比例显示图片的缩略图
  • .NET/C# 使用 SpanT 为字符串处理提升性能
  • .net程序集学习心得
  • .NET中的十进制浮点类型,徐汇区网站设计
  • @四年级家长,这条香港优才计划+华侨生联考捷径,一定要看!
  • [ solr入门 ] - 利用solrJ进行检索
  • [ 渗透测试面试篇 ] 渗透测试面试题大集合(详解)(十)RCE (远程代码/命令执行漏洞)相关面试题
  • [.NET 即时通信SignalR] 认识SignalR (一)
  • [AHOI2009]中国象棋 DP,递推,组合数