SpringBoot原始碼解析-controller層引數的封裝

吾乃上將軍邢道榮發表於2019-04-09

在進入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<HandlerMethodArgumentResolver> resolvers = getDefaultArgumentResolvers();
			this.argumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);
		}
		...
	}
	
	private List<HandlerMethodArgumentResolver> getDefaultArgumentResolvers() {
		List<HandlerMethodArgumentResolver> 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就是在這邊注入進容器的。


返回目錄

相關文章