spring MVC源码探索之AbstractHandlerMethodMapping
创始人
2024-02-22 16:57:47
0

AbstractHandlerMethodMapping 是什么

官方解释是这样的。

/*** Abstract base class for {@link HandlerMapping} implementations that define* a mapping between a request and a {@link HandlerMethod}.** 

For each registered handler method, a unique mapping is maintained with* subclasses defining the details of the mapping type {@code }.* @param The mapping for a {@link HandlerMethod} containing the conditions* needed to match the handler method to incoming request.*/ public abstract class AbstractHandlerMethodMapping extends AbstractHandlerMapping implements InitializingBean

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

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

initHandlerMethods()

/**在初始化的时候发现 handler methods* Detects handler methods at initialization.*/@Overridepublic 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容器中所有beanString[] 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 methods = MethodIntrospector.selectMethods(userType,(MethodIntrospector.MetadataLookup) 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是一个注册表

 

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
有效的括号 一、题目 给定一个只包括 '(',')','{','}'...
【Ctfer训练计划】——(三... 作者名:Demo不是emo  主页面链接:主页传送门 创作初心ÿ...