Spring boot基于@Valid和@Validated验证List集合_我高考零分!的博客-优快云博客
使用场景
因为作为接口提供方,需要提供以List<E> 为请求参数的接口。
并且需要对列表的元素字段进行校验,例如非空等。
发现直接这样使用
public ResponseInfo xxx(@RequestBody @Validated List<E> list)
是不生效的。参数无法校验。
无论替换 @Validated 和 @Valid
甚至
public ResponseInfo xxx(@RequestBody List<@Valid E> list)
都使用过,依然无法生效
解决方案
@Validated
public class xxxController {
public ResponseInfo xxx(@RequestBody @Valid List<E> list){}
}
这样即可
在Springboot中,当需要对List类型的请求参数进行校验时,直接使用@Valid或@Validated可能无效。文章提到了两种尝试但未成功的写法,并给出了解决方案:使用`@Validated`注解修饰方法,然后在List前加上`@Valid`,如`@RequestBody@ValidList<E>list`,这样可以正确地对列表元素进行校验。
531

被折叠的 条评论
为什么被折叠?



