在进入DispatcherServlet的时候,spring容器会得到一个HttpServletRequest对象,但是我们在使用controller层方法时,经常会使用RequestBody,RequestHeader等注解将该对象封装成更便于操作的对象类型。那么在我们使用RequestBody等注解的时候,中间经历了怎样的转换逻辑。今天就来解析一下。
参数解析逻辑
首先找到代码封装的位置,进入InvocableHandlerMethod的invokeForRequest方法(调用链可以自行找一下,idea的debug功能很方便)。
public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,Object... providedArgs) throws Exception {
//这行就是获取参数的逻辑Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
if(logger.isTraceEnabled()) {logger.trace("Arguments: "+ Arrays.toString(args));}
//执行controller方法returndoInvoke(args);}protected Object[] getMethodArgumentValues(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,Object... providedArgs) throws Exception {MethodParameter[] parameters = getMethodParameters();
Object[] args = new Object[parameters.length];
...if(this.argumentResolvers.supportsParameter(parameter)) {try {
//逐个解析方法参数args[i] = this.argumentResolvers.resolveArgument(parameter, mavContainer, request, this.dataBinderFactory);continue;
}...returnargs;}public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
//获取对应的参数解析器HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter);
if(resolver == null) {throw new IllegalArgumentException("Unknown parameter type ["+ parameter.getParameterType().getName() +"]");}
//执行解析逻辑returnresolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
}private HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) {HandlerMethodArgumentResolver result = this.argumentResolverCache.get(parameter);
if(result == null) {for(HandlerMethodArgumentResolver methodArgumentResolver : this.argumentResolvers) {
//遍历解析器,supportsParameter方法返回true就可以if(methodArgumentResolver.supportsParameter(parameter)) {result = methodArgumentResolver;
this.argumentResolverCache.put(parameter, result);break;}}}returnresult;}
整个解析的逻辑还比较清晰:
获取方法需要的参数类型,逐个解析
调用解析器的supportsParameter方法,判断是否支持参数类型
调用解析器的resolveArgument方法,解析参数
参数解析示范
在这个就以最常用的RequestHeader,和RequestBody来分析一下解析的流程。
首先是RequestHeader
RequestHeader 对应的解析器为RequestHeaderMethodArgumentResolver。
先查看supportsParameter方法:
public boolean supportsParameter(MethodParameter parameter) {
//判断参数是否为RequestHeader注解标记,并且类型不为mapreturn(parameter.hasParameterAnnotation(RequestHeader.class) &&!Map.class.isAssignableFrom(parameter.nestedIfOptional().getNestedParameterType()));}
接下来查看resolveArgument方法,这个方法在他的父类中:
public final Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
//获取注解信息NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);
MethodParameter nestedParameter = parameter.nestedIfOptional();
//获取header的nameObject resolvedName = resolveStringValue(namedValueInfo.name);
if(resolvedName == null) {...}
//通过name查找Object arg = resolveName(resolvedName.toString(), nestedParameter, webRequest);
if(arg == null) {...}if(binderFactory != null) {WebDataBinder binder = binderFactory.createBinder(webRequest, null, namedValueInfo.name);
try {
//处理类型转换之类的问题arg = binder.convertIfNecessary(arg, parameter.getParameterType(), parameter);
}...}handleResolvedValue(arg, namedValueInfo.name, parameter, mavContainer, webRequest);returnarg;}
逻辑很清晰,关键代码就在resolveName方法里了,进入该方法:
protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {String[] headerValues = request.getHeaderValues(name);
if(headerValues != null) {return(headerValues.length == 1 ? headerValues[0] : headerValues);}else{returnnull;}}
这边就可以清晰的看到获取的过程了。
接下来看看RequestBody
RequestBody注解对应的解析器为RequestResponseBodyMethodProcessor
首先还是查看supportsParameter方法:
public boolean supportsParameter(MethodParameter parameter) {
//判断是否有RequestBody注解returnparameter.hasParameterAnnotation(RequestBody.class);}
接下来查看resolveArgument方法:
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {parameter = parameter.nestedIfOptional();
//解析传入请求的请求体Object arg =readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());
String name = Conventions.getVariableNameForParameter(parameter);
if(binderFactory != null) {WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name);
if(arg != null) {
//如果有需要的话校验相关参数validateIfApplicable(binder, parameter);...}...}returnadaptArgumentIfNecessary(arg, parameter);}
讲到这儿可以发现参数解析的逻辑大同小异,那么springboot到底内置了多少解析器呢?
在DispatcherServlet中,根据mapping获取到了相应的方法后,还需要找到相应的HandlerAdapter去执行。当我们使用RequestMapping注解时,使用的就是RequestMappingHandlerAdapter这个类。查看该类的afterPropertiesSet方法()。
public voidafterPropertiesSet() {
// Do this first, it may add ResponseBody advice beansinitControllerAdviceCache();
if(this.argumentResolvers == null) {
//获取解析器的方法就在这里List resolvers = getDefaultArgumentResolvers();
this.argumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);
}...}private ListgetDefaultArgumentResolvers() {List resolvers = new ArrayList<>();
// Annotation-based argument resolutionresolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(),false));
resolvers.add(new RequestParamMapMethodArgumentResolver());
resolvers.add(new PathVariableMethodArgumentResolver());
resolvers.add(new PathVariableMapMethodArgumentResolver());
resolvers.add(new MatrixVariableMethodArgumentResolver());
resolvers.add(new MatrixVariableMapMethodArgumentResolver());
resolvers.add(new ServletModelAttributeMethodProcessor(false));
resolvers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(),
this.requestResponseBodyAdvice));
resolvers.add(new RequestPartMethodArgumentResolver(getMessageConverters(),
this.requestResponseBodyAdvice));
resolvers.add(new RequestHeaderMethodArgumentResolver(getBeanFactory()));
resolvers.add(new RequestHeaderMapMethodArgumentResolver());
resolvers.add(new ServletCookieValueMethodArgumentResolver(getBeanFactory()));
resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory()));
resolvers.add(new SessionAttributeMethodArgumentResolver());
resolvers.add(new RequestAttributeMethodArgumentResolver());
// Type-based argument resolutionresolvers.add(new ServletRequestMethodArgumentResolver());
resolvers.add(new ServletResponseMethodArgumentResolver());
resolvers.add(new HttpEntityMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice));
resolvers.add(new RedirectAttributesMethodArgumentResolver());
resolvers.add(new ModelMethodProcessor());
resolvers.add(new MapMethodProcessor());
resolvers.add(new ErrorsMethodArgumentResolver());
resolvers.add(new SessionStatusMethodArgumentResolver());
resolvers.add(new UriComponentsBuilderMethodArgumentResolver());
// Custom argumentsif(getCustomArgumentResolvers() != null) {resolvers.addAll(getCustomArgumentResolvers());}
// Catch-allresolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(),true));
resolvers.add(new ServletModelAttributeMethodProcessor(true));
returnresolvers;}
在getDefaultArgumentResolvers方法中,我们可以看到springboot内置了很多的参数解析器。我们上面说到的RequestResponseBodyMethodProcessor,RequestHeaderMethodArgumentResolver就是在这边注入进容器的。
在此我向大家推荐一个架构学习交流群。交流学习群号:938837867 暗号:555 里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化、分布式架构等这些成为架构师必备