Validated框架
spring-boot项目引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
实体类
@Data
public class OrderInfo {
@NotNull(message = "Aid not null",groups = {AValidated.class})
@NotNull(message = "Bid not null",groups = {BValidated.class})
private String id;
@Valid
private Producted producted;
}
@Data
public class Producted {
@NotNull(message = "proId not null")
private String proId;
private String proPrice;
}
可以通过groups进行分组
两个接口:AValidated 和BValidated
public interface AValidated {
}
public interface BValidated {
}
使用groups属性
对象参数前的@Validated(AValidated.class)表示会按OrderInfo中groups = {AValidated.class}的注解进行校验
@RestController
public class validatedController {
? @PostMapping("/validatedTestA")
? public void validatedTestA(@RequestBody @Validated(AValidated.class) OrderInfo info){
? System.out.println(info);
? }
? @PostMapping("/validatedTestB")
? public void validatedTestB(@RequestBody @Validated(BValidated.class) OrderInfo info){
? System.out.println(info);
? }
}
嵌套校验
对于OrderInfo的属性,只需要在类的成员变量上加校验注解即可
但如果要对OrderInfo的属性Producted中的属性进行校验,除了要在Producted中的属性加校验注解之外
最重要的是在Producted上加上 @Valid注解