前言
这篇文章主要是探讨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(this

最低0.47元/天 解锁文章
1612

被折叠的 条评论
为什么被折叠?



