SpringBoot源码解析-controller层参数的封装

在进入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方法
		return doInvoke(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;
				}
				...
		return args;
	}

	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() + "]");
		}
		//执行解析逻辑
		return resolver.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;
				}
			}
		}
		return result;
	}
复制代码

整个解析的逻辑还比较清晰:

  1. 获取方法需要的参数类型,逐个解析
  2. 调用解析器的supportsParameter方法,判断是否支持参数类型
  3. 调用解析器的resolveArgument方法,解析参数

参数解析示范

在这个就以最常用的RequestHeader,和RequestBody来分析一下解析的流程。

首先是RequestHeader

RequestHeader 对应的解析器为RequestHeaderMethodArgumentResolver。

先查看supportsParameter方法:

	public boolean supportsParameter(MethodParameter parameter) {
	    //判断参数是否为RequestHeader注解标记,并且类型不为map
		return (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的name
		Object 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);

		return arg;
}

复制代码

逻辑很清晰,关键代码就在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 {
			return null;
		}
	}
复制代码

这边就可以清晰的看到获取的过程了。

接下来看看RequestBody

RequestBody注解对应的解析器为RequestResponseBodyMethodProcessor

首先还是查看supportsParameter方法:

	public boolean supportsParameter(MethodParameter parameter) {
	//判断是否有RequestBody注解
		return parameter.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);
				...
			}
			...
		}

		return adaptArgumentIfNecessary(arg, parameter);
	}
复制代码

首先解析请求体,其次校验结果,这样就是我们拿到的RequestBody对象了。这个地方解析和校验相关的逻辑,我们是可以做点文章的具体可以查看:SpringBoot踩坑日记-一个非空校验引发的bug


讲到这儿可以发现参数解析的逻辑大同小异,那么springboot到底内置了多少解析器呢?

在DispatcherServlet中,根据mapping获取到了相应的方法后,还需要找到相应的HandlerAdapter去执行。当我们使用RequestMapping注解时,使用的就是RequestMappingHandlerAdapter这个类。查看该类的afterPropertiesSet方法()。

	public void afterPropertiesSet() {
		// Do this first, it may add ResponseBody advice beans
		initControllerAdviceCache();

		if (this.argumentResolvers == null) {
			//获取解析器的方法就在这里
			List resolvers = getDefaultArgumentResolvers();
			this.argumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);
		}
		...
	}
	
	private List getDefaultArgumentResolvers() {
		List resolvers = new ArrayList<>();

		// Annotation-based argument resolution
		resolvers.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 resolution
		resolvers.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 arguments
		if (getCustomArgumentResolvers() != null) {
			resolvers.addAll(getCustomArgumentResolvers());
		}

		// Catch-all
		resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), true));
		resolvers.add(new ServletModelAttributeMethodProcessor(true));

		return resolvers;
	}
复制代码

在getDefaultArgumentResolvers方法中,我们可以看到springboot内置了很多的参数解析器。我们上面说到的RequestResponseBodyMethodProcessor,RequestHeaderMethodArgumentResolver就是在这边注入进容器的。


返回目录

转载于:https://juejin.im/post/5cabfce46fb9a0685a3edf7d

你可能感兴趣的:(SpringBoot源码解析-controller层参数的封装)