首页 > 解决方案 > Spring 在转换后验证控制器参数。它可以在转换前验证吗?

问题描述

假设我有一个类 Dog,其字段 numberOfLegs 被验证为 4 或更少。

class Dog {

    @Max(4)
    int numberOfLegs;
}

这是控制器方法的参数,如果验证失败,则 Spring 在响应中发送相关的错误消息。

但是,该请求实际上发送了一个 DogRestDto。

class DogRestDto {

    @Max(4)
    int legs;
}

我使用转换器将其更改为 Dog 以供我的控制器使用,但验证是在 Dog 而不是 DogRestDto 上完成的,并且错误消息谈论dog.numberOfLegs而不是dog.legs.

有没有一种简单的方法来告诉 Spring 在转换之前对 REST dto 进行验证,以便错误消息对客户端更有意义?

标签: validationspring-mvcdata-bindingtype-conversion

解决方案


I've achieved this by overriding the mvcUriComponentsContributor method in my DelegatingWebMvcConfiguration to replace the RequestResponseBodyMethodProcessor in the requestMappingHandlerAdapter's argumentResolvers with a implementation that validates the REST DTO. It obtains the REST DTO from a request-scoped bean that I've made to hold the source object currently being converted, which is populated by my implementation of the GenericConversionService.

It's not very pretty. I'd love it if Spring gave me a cleaner way to do this.


推荐阅读