简介
Bean Validation是Java定义的一套基于注解的数据校验规范,在SpringBoot中已经集成在 starter-web中,所以无需在添加其他依赖。
注
:SpringBoot 2.3.0 以后需要手动引入validation。。。。
- pom.xml如下
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
约束注解
在javax.validation.constraints
内置了constraint注解
注解 | 作用 | 参数详情 | 类型要求 | 是否允许null |
---|---|---|---|---|
@AssertTrue | 元素必须为 true | 无 | boolean/Boolean | 允许null |
@AssertFalse | 元素必须为 false | 无 | boolean/Boolean | 允许null |
@DecimalMax | 元素必须小于等于指定的最大值 | value:最大值 | BigDecimal/BigInteger/CharSequence/byte/short/int/long(包括其封装类型) | 允许null |
@DecimalMin | 元素必须大于等于指定的最小值 | value:最小值 | BigDecimal/BigInteger/CharSequence/byte/short/int/long(包括其封装类型) | 允许null |
@Digits(integer,fraction) | 元素必须在指定的范围内 | integer:最大整数位数;fraction:最大小数位数 | BigDecimal/BigInteger/byte/short/int/long(包括其封装类型) | 允许null |
元素必须是电子邮箱地址 | 无 | CharSequence | ||
@Future | 元素必须是一个将来的日期 | 无 | Date,Calendar,LocalDate,LocalDateTime,等 | 允许null |
@FutureOrPresent | 元素必须是一个现在/将来的日期 | 无 | Date,Calendar,LocalDate,LocalDateTime,等 | 允许null |
@Max | 元素必须小于等于指定的最大值 | value:最大值 | BigDecimal/BigInteger/byte/short/int/long(包括其封装类型) | 允许null |
@Min | 元素必须大于等于指定的最小值 | value:最小值 | BigDecimal/BigInteger/byte/short/int/long(包括其封装类型) | 允许null |
@Negative | 元素必须是负数(0不是负数) | 无 | BigDecimal/BigInteger/byte/short/int/long/float/double(包括其封装类型) | 允许null |
@NegativeOrZero | 元素必须是负数(包括0) | 无 | BigDecimal/BigInteger/byte/short/int/long/float/double(包括其封装类型) | 允许null |
@NotBlank | 元素必须是不能为null,并且必须至少包含一个非空白字符 | 无 | CharSequence | |
@NotEmpty | 元素必须是不能为null或空内容 | 无 | CharSequence/Map/Collection/数组 | |
@NotNull | 元素必须是不为null | 无 | 任何类型 | |
@Null | 元素必须是null | 无 | 任何类型 | |
@Past | 被注释的元素必须是一个过去的日期 | 无 | Date,Calendar,LocalDate,LocalDateTime,等 | 允许null |
@PastOrPresent | 被注释的元素必须是一个过去/现在的日期 | 无 | Date,Calendar,LocalDate,LocalDateTime,等 | 允许null |
@Pattern | 元素必须符合指定的正则表达式 | regexp:正则表达式 | CharSequence | 允许null |
@Positive | 元素必须是正数(0不是正数) | 无 | BigDecimal/BigInteger/byte/short/int/long/float/double(包括其封装类型) | 允许null |
@PositiveOrZero | 元素必须是正数(包括0) | 无 | BigDecimal/BigInteger/byte/short/int/long/float/double(包括其封装类型) | 允许null |
@Size | 元素大小必须在指定的边界(包括)之间 | min:元素的大小必须大于或等于min;max:元素的大小必须小于或等于max | CharSequence(length)/Collection(size)/Map(size)/数组(length) | 允许null |
校验规则
校验分为在方法里面校验和在bean对象里面校验
方法校验
在方法里面校验,违反约束,会抛出ConstraintViolationException
异常
- eg
- controller
@RequestMapping("/student") @RestController @Slf4j @Validated public class StudentController { @GetMapping("/validate") @ResponseBody public String validate( @NotBlank(message = "number不为空") @RequestParam("number") String number, @NotBlank(message = "name不为空") @RequestParam("name") String name, @Min(value = 1,message = "性别错误") @Max(value = 2,message = "性别错误") @NotNull(message = "sex不为空") @RequestParam("sex") Integer sex, @RequestBody @Min(value = 10,message = "年龄最小为10") @Max(value = 100,message = "年龄最大为100") @NotNull(message = "age不为空") @RequestParam("age") Integer age, @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull(message = "birthdayTime不为空") @Past(message = "birthdayTime错误") Date birthdayTime){ return "validate"; } }
- controller
对象校验
在bean对象里面校验,违反约束,会抛出MethodArgumentNotValidException
异常
- eg
- controller
@PostMapping("") public Integer add(@Validated @RequestBody Student student){ return studentService.addStudent(student); }
- pojo
public class Student { @NotBlank(message = "number不为空") private String number; @NotBlank(message = "name不为空") private String name; @Min(value = 1,message = "性别错误") @Max(value = 2,message = "性别错误") @NotNull(message = "sex不为空") private Integer sex; @Min(value = 10,message = "年龄最小为10") @Max(value = 100,message = "年龄最大为100") @NotNull(message = "age不为空") private Integer age; @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull(message = "birthdayTime不为空") @Past(message = "birthdayTime错误") private Date birthdayTime; }
- controller
@Validated
和@Valid
区别
Spring Validation验证框架对参数的验证机制提供了@Validated(Spring’s JSR-303规范,是标准JSR-303的一个变种),javax提供了@Valid(标准JSR-303规范),配合BindingResult可以直接提供参数验证结果。
在检验入参是否符合规范时,使用@Validated或者@Valid在基本验证功能上没有太多区别。但是在分组、注解地方、嵌套验证等功能上两个有所不同:
分组
-
注解地方
- @Validated:可以用在类型、方法和方法参数上。但是不能用在成员属性(字段)上
- @Valid:可以用在方法、构造函数、方法参数和成员属性(字段)上
-
嵌套验证
- @Validated:用在方法入参上无法单独提供嵌套验证功能。不能用在成员属性(字段)上,也无法提示框架进行嵌套验证。能配合嵌套验证注解@Valid进行嵌套验证
- @Valid:用在方法入参上无法单独提供嵌套验证功能。能够用在成员属性(字段)上,提示验证框架进行嵌套验证。能配合嵌套验证注解@Valid进行嵌套验证
分组校验
通常一个pojo对象可以有多种用途,如添加,更新,查询等,而它们的约束条件往往是不一样的,这时就可以利用分组校验的方式进行验证,以下是一个简单的例子
pojo
public class Student {
@NotBlank(message = "number不为空",groups = Add.class)
@Null(message = "number必须空",groups = Update.class)
private String number;
@NotBlank(message = "name不为空",groups = Add.class)
private String name;
@Min(value = 1,message = "性别错误",groups = {Add.class,Update.class})
@Max(value = 2,message = "性别错误",groups = {Add.class,Update.class})
@NotNull(message = "sex不为空",groups = Add.class)
private Integer sex;
@Min(value = 10,message = "年龄最小为10",groups = {Add.class,Update.class})
@Max(value = 100,message = "年龄最大为100",groups = {Add.class,Update.class})
@NotNull(message = "age不为空",groups = Add.class)
private Integer age;
@DateTimeFormat(pattern = "yyyy-MM-dd")
@NotNull(message = "birthdayTime不为空",groups = Add.class)
@Past(message = "birthdayTime错误",groups = {Add.class,Update.class})
private Date birthdayTime;
}
controller
@PostMapping("")
public Integer add(@Validated(Add.class) @RequestBody Student student){
return studentService.addStudent(student);
}
@PutMapping("/{number}")
public Boolean update(@PathVariable String number,@Validated(Update.class) @RequestBody Student student){
student.setNumber(number);
return studentService.updateStudent(student);
}