spring MVC源码探索


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是一个注册表

#Java##Spring#
全部评论
学到了,感谢大佬的分享
点赞 回复 分享
发布于 2022-09-14 20:39 陕西

相关推荐

重生我想学测开:嵌入式的问题,我准备入行京东外卖了
点赞 评论 收藏
分享
04-06 11:24
已编辑
太原学院 C++
真烦好烦真烦:感觉不太对劲,这种主动加微信的一般都是坑,要小心辨别
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
05-29 22:21
Offer1:小马智行,深圳,测试开发工程师,17.0k*16.0,Offer2:追觅科技,深圳,嵌入式工程师,18.0k*15.0,
嵌软狗都不学:各位base深圳的同事,作为也是并肩作战的一员,今天想站在管理视角,和大家开诚布公地聊一聊:从近几个月的上下班数据对比看来,我们发现一个明显的差异:深圳同事的在岗时间普遍比苏州同事短。很多深圳同事早上9点之后才到公司,晚上不到 20 点就下班了;而总部那边,20点半甚至 22 点后还有不少同事在办公室忙碌,特别是研发团队,加班更是常态。相信去过苏州的同事,对这种场景都不陌生。我很好奇,这是因为苏州工作任务太重还是咱们深圳同事效率真的高到能在更短时间内完成工作?MOVA在深圳成立分公司是为了吸引更优秀的人才贡献更多更高质的价值,公司管理层给我反馈的是深圳招到的多是行业的专家大拿,大部分都是薪资比苏州高的,而且我们办公的租金等也远高于苏州的..MOVA虽脱胎于强壮的集团母体不久,各业务板块尚未实现全面盈利,虽说公司管理层目光长远,不纠结当下的人才投入,但行业内的普遍标准是,员工创造的价值要达到公司雇佣成本的 15 倍以上。大家不妨自我审视一下,自己是否达到了这个标准?如果是抱着划水、按时打卡走人拿毛爷爷的心态那不适合来MOVA,那样过下去不但自己过得尴尬也会影响MOVA这个大船的攻城略地的速度.我并非鼓励大家盲目加班,而是倡导高效工作,拒绝无效忙碌,不要让项目进度因低效受影响,也别把精力浪费在和苏州同事拼打卡时长上,提倡更高的人效比;考虑到两地地域和交通差异,相信大家会找最适合自己发挥的工作方式(比如按时下班后1小时到家晚饭后继续未竟工作等..)大家在遵守公司规章的情况下尽情地体现自己的能力价值,为MOV!和深圳公司争光我们在这边才能更安心更有信心的工作下去;请客BU长、名部门长、项目管理和各业务单元负责人,全面梳理团队情况,及时评估成员工作负荷与成果质量,坚决清退划水害虫痕疫,践行公司价值观,相互监督,防止管理漏洞及渎职。感谢人家的理解,也请人家多担待我的直言不讳……
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务