Spring Boot @Valid 未生效排查清单

背景

这篇文章主要给大家介绍了关于 Spring Boot 中 @Valid 注解不生效的排查清单。

可能一:依赖配置

一开始使用了 spring-boot-starter-validation,升级之后无效了,可能是缺少了 hibernate-validator 依赖。原因是 Spring Boot 2.3 之后,官方就移除了其中包含的 hibernate-validator 依赖。

需要手动增加下面的依赖

1
2
3
4
5
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.5.Final</version>
</dependency>

可能二:嵌套对象

如果是嵌套对象的话,里面的对象还要添加 @Valid注解,有问题的代码案例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Operation(summary = "我是 swagger api 接口说明")
@PostMapping("/frontapi/v1/foo")
public StandardHttpResponse<String> update(
@Valid @RequestBody CommonListRequest<UpdateRequest> request) {
...
}

@Data
public class CommonListRequest<T> {

@NotEmpty
@Schema(description = "业务数据")
@Size(min = 1, max = 1000)
private List<T> data;
}

@Data
public class UpdateRequest {
@NotEmpty
@Schema(description = "配置", example = "{}")
private String flowConfigWithNode;
}

验证命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 模拟 flowConfigWithNode key 填错,无报错
curl -X "POST" "http://127.0.0.1:8080/frontapi/v1/foo" \
-H 'Content-Type: application/json' \
-d $'{
"data": [
{
"flowConfigWithNodes": "{}"
}
]
}'

# 模拟 data key 填错,有报错
curl -X "POST" "http://127.0.0.1:8080/frontapi/v1/foo" \
-H 'Content-Type: application/json' \
-d $'{
"dataa: [
{
"flowConfigWithNode": "{}"
}
]
}'

正确的代码, 调整 CommonListRequest 即可,在 data 属性上增加 @Valid 注解即可。

1
2
3
4
5
6
7
8
9
@Data
public class CommonListRequest<T> {

@Valid
@NotNull
@Schema(description = "业务数据")
@Size(min = 1, max = 1000)
private List<T> data;
}