spring boot 自定义参数解析器不生效问题排查

2019-06-29  本文已影响0人  soSweety

首先添加自定义的参数解析器

public  class  TimezoneTransferResolver  implement  HandlerMethodArgumentResolver  {


@Override
boolean  supportsParameter(MethodParameter  parameter)  {
return    parameter.hasMethodAnnotation(TimezoneTransfer::class.java);
}

@Override
Object  resolveArgument(MethodParameter  parameter,  ModelAndViewContainer  mavContainer,
NativeWebRequest  webRequest,  WebDataBinderFactory  binderFactory)  throws  Exception{}

}

编写注解及添加解析器

注意以下是 Kotlin 代码编写

@Retention(RetentionPolicy.RUNTIME)
@Target(AnnotationTarget.FUNTION)
annotation  class  TimezoneTransfer



@Configuration
open  class  CommonMvcConfig  :  WebMvcConfigurerAdapter()  {


        @Bean
        open  fun  timezoneTransfer():  TimezoneTransferResolver  {
                return  TimezoneTransferResolver()
        }


        override  fun  addArgumentResolvers(argumentResolvers:  MutableList<HandlerMethodArgumentResolver>)  {
                argumentResolvers.add(timezoneTransfer())
        }

}

在接口参数上添加注解

@PostMapping(value  =  "/league")
@TimezoneTransfer
fun  getBetInfo(@RequestBody  queryBankerMatchInfoPO:  QueryBankerMatchInfoPO):  BizResponse<MatchLeagueInfoPageVO>  {
        logger.info("league-bet:  "  +  queryBankerMatchInfoPO.startAt?.toString()    +  ","  +  queryBankerMatchInfoPO.endAt?.toString())
        return  BizResponse(bankerInfoXService.getLeagueInfo(getCustomerId(),  queryBankerMatchInfoPO,  getUserLang()))
}

启动项目发现自定义解析器无效

定位问题

首先分析spring boot 解析参数的过程
spring boot 是在 RequestMappingHandlerAdapter 类的invokeHandlerMethod方法中,处理请求

protected  ModelAndView  invokeHandlerMethod(HttpServletRequest  request,
HttpServletResponse  response,  HandlerMethod  handlerMethod)  throws  Exception  {

ServletWebRequest  webRequest  =  new  ServletWebRequest(request,  response);
try  {
WebDataBinderFactory  binderFactory  =  getDataBinderFactory(handlerMethod);
ModelFactory  modelFactory  =  getModelFactory(handlerMethod,  binderFactory);

ServletInvocableHandlerMethod  invocableMethod  =  createInvocableHandlerMethod(handlerMethod);
invocableMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
invocableMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
invocableMethod.setDataBinderFactory(binderFactory);
invocableMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer);

ModelAndViewContainer  mavContainer  =  new  ModelAndViewContainer();
mavContainer.addAllAttributes(RequestContextUtils.getInputFlashMap(request));
modelFactory.initModel(webRequest,  mavContainer,  invocableMethod);
mavContainer.setIgnoreDefaultModelOnRedirect(this.ignoreDefaultModelOnRedirect);

AsyncWebRequest  asyncWebRequest  =  WebAsyncUtils.createAsyncWebRequest(request,  response);
asyncWebRequest.setTimeout(this.asyncRequestTimeout);

WebAsyncManager  asyncManager  =  WebAsyncUtils.getAsyncManager(request);
asyncManager.setTaskExecutor(this.taskExecutor);
asyncManager.setAsyncWebRequest(asyncWebRequest);
asyncM anager.registerCallableInterceptors(this.callableInterceptors);
asyncManager.registerDeferredResultInterceptors(this.deferredResultInterceptors);

if (asyncManager.hasConcurrentResult()) {
Object result = asyncManager.getConcurrentResult();
mavContainer = (ModelAndViewContainer) asyncManager.getConcurrentResultContext()[0];
asyncManager.clearConcurrentResult();
if (logger.isDebugEnabled()) {
logger.debug("Found concurrent result value [" + result + "]");
}
invocableMethod = invocableMethod.wrapConcurrentResult(result);
}

invocableMethod.invokeAndHandle(webRequest, mavContainer);
if (asyncManager.isConcurrentHandlingStarted()) {
return null;
}

return getModelAndView(mavContainer, modelFactory, webRequest);
}
finally {
webRequest.requestCompleted();
}
}

在invokeHandlerMethod方法中会创建一个ServletInvocableHandlerMethod,并且会设置参数解析器,详见代码段

invocableMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);

并且会用invocableMethod进一步处理请求

invocableMethod.invokeAndHandle(webRequest, mavContainer);

进入ServletInvocableHandlerMethod的invokeAndHandle方法
看到这行代码

Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs);

查看invokeForRequest方法

public Object invokeForRequest(NativeWebRequest request, ModelAndViewContainer mavContainer,
Object... providedArgs) throws Exception {

Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
if (logger.isTraceEnabled()) {
logger.trace("Invoking '" + ClassUtils.getQualifiedMethodName(getMethod(), getBeanType()) +
"' with arguments " + Arrays.toString(args));
}
Object returnValue = doInvoke(args);
if (logger.isTraceEnabled()) {
logger.trace("Method [" + ClassUtils.getQualifiedMethodName(getMethod(), getBeanType()) +
"] returned [" + returnValue + "]");
}
return returnValue;
}

发现参数在下面的代码段解析

Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);

在这方法中,会循环迭代参数,将其解析

private Object[] getMethodArgumentValues(NativeWebRequest request, ModelAndViewContainer mavContainer,
Object... providedArgs) throws Exception {

MethodParameter[] parameters = getMethodParameters();
Object[] args = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
MethodParameter parameter = parameters[i];
parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
args[i] = resolveProvidedArgument(parameter, providedArgs);
if (args[i] != null) {
continue;
}
if (this.argumentResolvers.supportsParameter(parameter)) {
try {
args[i] = this.argumentResolvers.resolveArgument(
parameter, mavContainer, request, this.dataBinderFactory);
continue;
}
catch (Exception ex) {
if (logger.isDebugEnabled()) {
logger.debug(getArgumentResolutionErrorMessage("Failed to resolve", i), ex);
}
throw ex;
}
}
if (args[i] == null) {
throw new IllegalStateException("Could not resolve method parameter at index " +
parameter.getParameterIndex() + " in " + parameter.getMethod().toGenericString() +
": " + getArgumentResolutionErrorMessage("No suitable resolver for", i));
}
}
return args;
}

定位参数解析的代码

args[i] = this.argumentResolvers.resolveArgument(
parameter, mavContainer, request, this.dataBinderFactory);

进入resolveArgument方法

public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, 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);
}

发现参数解析器在这行获取

HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter);

查看getArgumentResolver方法便真相大白了

private HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) {
HandlerMethodArgumentResolver result = this.argumentResolverCache.get(parameter);
if (result == null) {
for (HandlerMethodArgumentResolver methodArgumentResolver : this.argumentResolvers) {
if (logger.isTraceEnabled()) {
logger.trace("Testing if argument resolver [" + methodArgumentResolver + "] supports [" +
parameter.getGenericParameterType() + "]");
}
if (methodArgumentResolver.supportsParameter(parameter)) {
result = methodArgumentResolver;
this.argumentResolverCache.put(parameter, result);
break;
}
}
}
return result;
}

这里会遍历所有的参数解析器,并调用HandlerMethodArgumentResolver的supportsParameter方法查看是否支持解析这个参数类型,
supportsParameter方法是在我们自定义参数解析器时要实现的方法,而this.argumentResolvers这个List里有所有的解析器,我们的解析器是
通过继承并覆写WebMvcConfigurerAdapter的addArgumentResolvers方法添加进this.argumentResolvers的,
由于spring boot 的 RequestResponseBodyMethodProcessor(@RequestBody的解析器)在我们的解析器之前,所以导致spring boot 使用的
还是默认解析器
于是解决方法就简单了,去除接口中的@RequestBody注解就ok了

@PostMapping(value = "/league")
@TimezoneTransfer
fun getBetInfo(queryBankerMatchInfoPO: QueryBankerMatchInfoPO): BizResponse<MatchLeagueInfoPageVO> {
    logger.info("league-bet: " + queryBankerMatchInfoPO.startAt?.toString()  + "," + queryBankerMatchInfoPO.endAt?.toString())
    return BizResponse(bankerInfoXService.getLeagueInfo(getCustomerId(), queryBankerMatchInfoPO, getUserLang()))
}

最好将注解像@RequestBody一样改成只能加参数上,以避免两个注解同时使用

另外:
按需求决定要不要依赖注入AbstractJackson2HttpMessageConverter的子类,如MappingJackson2HttpMessageConverter
如果依赖注入,将会与spring boot 使用同一个HTTP消息转换器,
如果你为这个Bean设置了参数,将会影响默认的http参数解析

上一篇下一篇

猜你喜欢

热点阅读