问题备忘:Cannot generate variable name for non-typed Collection parameter type

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hry2015/article/details/81913638

在spring mvc中,定义如下RequestMapping方法

@RequestMapping(value="queryList",method = RequestMethod.POST)
@ResponseBody
public String queryList(HttpSession httpSession,@RequestBody(required = false) List<String> taskIds){
        String rtn = "";
        …
       return rtn;
 }

以上方法在本地环境(window)和测试环境 (redhat)是可以正常被请求,但是发布到生产环境(debian8.8)被请求时,却抛出以下异常:

2018-08-14 16:40:33.157 [https-jsse-nio-8443-exec-10] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [/icc-interface] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: Cannot generate variable name for non-typed Collection parameter type] with root cause
java.lang.IllegalArgumentException: Cannot generate variable name for non-typed Collection parameter type
        at org.springframework.core.Conventions.getVariableNameForParameter(Conventions.java:119)
        at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:129)
        at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)

定位到源码:抛出异常的原因是程序无法解析出集合中实际的类型,不知道什么原因集合中的真正类型丢失了,程序无法根据集合真正元素的类型生成对象实例

public static String getVariableNameForParameter(MethodParameter parameter) {
    Assert.notNull(parameter, "MethodParameter must not be null");
    Class<?> valueClass;
    boolean pluralize = false;

    if (parameter.getParameterType().isArray()) {
        valueClass = parameter.getParameterType().getComponentType();
        pluralize = true;
    }
    else if (Collection.class.isAssignableFrom(parameter.getParameterType())) {
              // 看源码是程序无法解析出集合中实际的类型
        valueClass = ResolvableType.forMethodParameter(parameter).asCollection().resolveGeneric();
        if (valueClass == null) {
            throw new IllegalArgumentException(
                "Cannot generate variable name for non-typed Collection parameter type");
        }
        pluralize = true;
    }
    else {
    …
          }
    …
    }

尝试将JDK8升级到最新版本,但是问题还是存在,最后在网上找到如下的解决方法:
重新定义StringList 类,直接带上集合的类型

public class StringList extends ArrayList<String> {
}

修改方法:使用StringList替换List

@RequestMapping(value="queryList",method = RequestMethod.POST)
@ResponseBody
public String queryList(HttpSession httpSession,@RequestBody(required = false)StringList  taskIds){
        String rtn = "";
        …
       return rtn;
 }

修正问题成功

猜你喜欢

转载自blog.csdn.net/hry2015/article/details/81913638