在开发的过程中,为了确保数据的准确性、可靠性和减少脏数据等,我们时常需要对入参进行校验,以往是通过条件判断去实现参数校验,但是这样费时费力又效果不好,而参数校验对于我们来说是一个非常高效的开发工具。
目录
一、基本使用
1、引入依赖
<!-- 参数校验 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2、实体类使用
给需要进行校验的字段加注解
@Data
@ApiModel(value = "user", description = "用户属性")
public class UserDTO {
@NotEmpty(message = "姓名不能为空")
@ApiModelProperty(value = "姓名")
private String userName;
@NotNull(message = "年龄不能为空")
@ApiModelProperty(value = "年龄")
private Integer userAge;
}
- @NotEmpty:集合对象的元素不为 0 ,即集合不为空 。
- @NotNull:不能为 null 。
3、Controller层使用
@PostMapping("/users")
@ApiOperation(value = "查询用户信息")
@ApiOperationSupport(order=1) //api文档排序
public UserVO getUser(@Validated @RequestBody UserDTO dto) {
return userService.getUser(dto);
}
Valid 和 Validated 区别
1.分组
@Validated:提供了一个分组功能,可以在入参验证时,根据不同的分组采用不同的验证机制。
@Valid:作为标准JSR-303规范,还没有吸收分组的功能。
2