一、继承结构
@RequestBody、@ResponseBody的处理器:RequestResponseBodyMethodProcessor
@ModelAttribute处理器: ModelAttributeMethodProcessor
HttpEntity处理器: HttpEntityMethodProcessor
参数值解析器: HandlerMethodArgumentResolver
返回值处理器: HandlerMethodReturnValueHandler
使用HttpMessageConverter 转换方法参数: AbstractMessageConverterMethodArgumentResolver
二、 处理过程
1. RequestResponseBodyMethodProcessor的resolveArgument过程
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
//返回@RequestBody需要的参数, Spring使用我们自定义的RequestBodyAdvice, ResponseBodyAdvice发生在这里 Object arg = readWithMessageConverters(webRequest, parameter, parameter.getGenericParameterType()); String name = Conventions.getVariableNameForParameter(parameter);
//输入参数转换成Java对象发生在这里,后面有专门的文章讲解,注意:每次请求绑定的对象的重新生成的 WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name); if (arg != null) { validateIfApplicable(binder, parameter); if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) { throw new MethodArgumentNotValidException(parameter, binder.getBindingResult()); } } mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult()); return arg; } @Override protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, MethodParameter methodParam, Type paramType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException { HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(servletRequest);
//调用父类的readWithMessageCoverters()方法 Object arg = readWithMessageConverters(inputMessage, methodParam, paramType); if (arg == null) { if (methodParam.getParameterAnnotation(RequestBody.class).required()) { throw new HttpMessageNotReadableException("Required request body is missing: " + methodParam.getMethod().toGenericString()); } } return arg; }