2

我刚刚从 Spring 3.0 升级到 3.2。我在我的 spring 配置 xml 文件中配置了一个这样的自定义参数解析器:

<mvc:annotation-driven>
  <mvc:argument-resolvers>
    <bean class="mycompany.api.PersonResolver" />   
  </mvc:argument-resolvers>
</mvc:annotation-driven>

我的 Spring MVC 控制器有一个这样的方法:

@RequestMapping(value="/api/doSomething", method=RequestMethod.POST)
public @ResponseBody JsonNode handleRestCall(Person person) {
  ...
  return jsonNode;
}

Person 类是我们自己的专有类。

但是,这不起作用。它给了我一个错误:

Rest call error argument type mismatch
HandlerMethod details: 
    Controller [MyController]
    ...
    Resolved arguments: 
    [0] [type=org.springframework.validation.support.BindingAwareModelMap] [value=    {org.springframework.validation.BindingResult.objectNode=org.springframework.validation.BeanPropertyBindingResult: 0 errors}]

    java.lang.IllegalArgumentException: argument type mismatch

似乎将我的 Person 参数类型更改为其他类型(在我的情况下:PersonWrapper,包含对 Person 的引用)为我提供了解决该问题的方法,即 Spring 现在可以解决该参数。

谁可以给我解释一下这个?这是因为 Spring 使用 java Reflection 并且与某些 Spring Person 类有一些名称冲突(Spring security 有一个 org.springframework.security.ldap.userdetails.Person 类)?

我的解析器的实现:我的初始实现如下所示:

import mycompany.Person;

public class PersonResolver implements HandlerMethodArgumentResolver  {
    public boolean supportsParameter(MethodParameter mp) {
      return mp.getParameterType().equals(Person.class);
}

    public Object resolveArgument(MethodParameter mp, ModelAndViewContainer mavc, NativeWebRequest nwr, WebDataBinderFactory wdbf) throws Exception {
      if(mp.getParameterType().equals(Person.class)) {
        ...
        return somePerson;
      }
      return UNRESOLVED;
    }
}

弹簧配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc   http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <context:annotation-config /> 

    <!-- automatically search for Controller classes using @Controller annotation -->
    <context:component-scan base-package="mycompany.api"/>

    <!-- we use Spring 3 annotation driven development -->
    <mvc:annotation-driven>
        <mvc:argument-resolvers>
                <bean class="mycompany.api.PersonResolver" />   
                <bean class="mycompany.api.SessionLocaleResolver"/>
        </mvc:argument-resolvers>
    </mvc:annotation-driven>

</beans>
4

0 回答 0