如何用Spring注解实现嵌套JSON对象的条件校验?
解决方案
要实现「传入location字段时校验其内部country和city非空,未传入则不校验」的需求,可通过Spring Validation的级联校验配合注解配置实现,具体步骤如下:
1. 确保引入Validation依赖
Spring Boot 2.3及以上版本需单独引入校验starter,Maven依赖配置如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
2. 修改POJO类配置
(1)在Person类的location字段添加@Valid
开启嵌套对象的级联校验,确保当location非空时,Spring会自动校验其内部字段:
public class Person { private String name; private int age; @Valid // 触发对Location对象的级联校验 private Location location; // Getters and Setters }
(2)完善Location类的校验注解
将@NotNull标注在字段上(或配合@JsonProperty标注在构造器参数上),明确非空约束:
public class Location { @NotNull(message = "country不能为空") private String country; @NotNull(message = "city不能为空") private String city; @JsonCreator public Location(@JsonProperty("country") @NotNull String country, @JsonProperty("city") @NotNull String city) { this.country = country; this.city = city; } // Getters and Setters }
注:构造器上的
@JsonProperty是为了让Jackson正确映射JSON字段到构造器参数,避免因参数名匹配问题导致校验失效。
3. 在控制器方法触发校验
在接收请求体的参数上添加@Valid注解,触发Spring的校验逻辑:
@RestController public class PersonController { @PostMapping("/person") public ResponseEntity<String> createPerson(@Valid @RequestBody Person person) { // 业务逻辑处理 return ResponseEntity.ok("操作成功"); } }
原@NotNull无效的原因
- 未开启级联校验:
Person类的location字段缺少@Valid注解,Spring不会自动校验嵌套的Location对象; - 构造器参数映射问题:未添加
@JsonProperty时,Jackson可能无法将JSON中的country/city正确绑定到构造器参数,导致@NotNull约束未被触发; - 未在控制器触发校验:请求参数未添加
@Valid/@Validated,Spring不会执行校验逻辑。
内容的提问来源于stack exchange,提问作者Sandy
相关产品推荐
相关产品推荐

