SpringBoot源码分析——请求参数注解分析

前言

这篇文章主要是探讨SpringBoot框架中,API接口的参数是如何解析并调用的。
从底层源码中分析并学习该框架思想,当然我们知道SpringBoot在很多方面都是用注解的切面灵活管理和调用,像@Bean,@Controller等等,配置方面也会用注解进行注入,这也是SpringBoot的灵魂所在。最近,在公司项目中也是用到注解来切入到API接口,解决文件流类型返回的Bug。在这里不深入探究SpringMVC流程,由于请求都是在DispatcherServlet转发处理,所以我们这次直接从doDispatch打断点开始分析SpringBoot2.6版本中是如何解析请求参数的,例如@PathVariable等。

分析

首先在doDispatch处打上断点,发起一个API请求。
在这里插入图片描述

由于之前SpringMVC源码分析过,知道主要的方法代理实现是在handle方法里
在这里插入图片描述

下面是handle的主要实现代码:

protected ModelAndView handleInternal(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
   
        this.checkRequest(request);
        ModelAndView mav;
        if (this.synchronizeOnSession) {
   
            HttpSession session = request.getSession(false);
            if (session != null) {
   
                Object mutex = WebUtils.getSessionMutex(session);
                synchronized(mutex) {
   
                    mav = this.invokeHandlerMethod(request, response, handlerMethod);
                }
            } else {
   
                mav = this.invokeHandlerMethod(request, response, handlerMethod);
            }
        } else {
   
            mav = this.invokeHandlerMethod(request, response, handlerMethod); // 这步是关键
        }

        if (!response.containsHeader("Cache-Control")) {
   
            if (this.getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) {
   
                this.applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers);
            } else {
   
                this.prepareResponse(response);
            }
        }

        return mav;
    }

发现主要调用了invokeHandlerMethod(request, response, handlerMethod)方法,代码如下

// 代码太长删减部分
protected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
   
        ServletWebRequest webRequest = new ServletWebRequest(request, response);

        Object result;
        try {
   
            WebDataBinderFactory binderFactory = this.getDataBinderFactory(handlerMethod); // 拿全限定类名去缓存找对应方法
            if (this.argumentResolvers != null) {
    //全部的参数解析器
                invocableMethod.setHandlerMethodArgumentResolvers(
  • 18
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值