【问题标题】:@RequestBody with generic type具有泛型类型的@RequestBody
【发布时间】:2016-05-23 22:19:32
【问题描述】:

我在使用 Spring MVC 4.2.6 和 Jackson (2.7.3) 时遇到了一些问题。我用一个使用泛型类型的方法创建了一个抽象的@RestController 类。我实现了这个传递泛型对象类型的抽象类。我使用@RequestBodyDispatcherServlet 抛出JsonMappingException(不能构造我的类的实例)。应用程序上下文中的MappingJackson2HttpMessageConverter 已配置。

编辑:添加了更多信息。

public abstract class AbsctractAnimalResource<DTO extends AnimalDTO> {

    // Doesn't work. Throws JsonMappingException. (@RequestBody)
    @RequestMapping(value = "/bar", method = POST, produces = APPLICATION_JSON_VALUE)
    public ResponseEntity<?> bar(@RequestBody DTO dto) throws Exception {
        return new ResponseEntity(dto, HttpStatus.CREATED);
    }

}

@RestController
@RequestMapping("/cat")
public class CatResource extends AbsctractAnimalResource<CatDTO> {

}

@RestController
@RequestMapping("/dog")
public class DogResource extends AbsctractAnimalResource<DogDTO> {

}


interface AnimalDTO { }
public class CatDTO implements AnimalDTO { }
public class DogDTO implements AnimalDTO { }

【问题讨论】:

  • 好的。添加了更多信息。谢谢。我无法理解,我调试了 DispatcherServlet 并且两个注解具有相同的行为,但是 @RequestBody 抛出了异常。

标签: java spring generics jackson


【解决方案1】:

在 Spring 4.2.6 类中进行了一些调试后,我发现了这个评论:

https://github.com/spring-projects/spring-framework/blob/4.2.x/spring-web/src/main/java/org/springframework/http/converter/json/AbstractJackson2HttpMessageConverter.java#L51

Spring 4.2.X 和 Jackson 2.7.X 不能一起工作。我将我的 Jackson 版本降级到 2.6.6,现在一切正常。 Spring 4.3.X 与 Jackson 2.7+ 配合得很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2015-07-09
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多