依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
开启参数校验
在接口参数前增加 @Validated
注解
@PostMapping("update")
public R<Boolean> update(@RequestBody @Validated UserInfoDTO report) {
// todo something
return R.success(Boolean.TRUE);
}
普通校验
/**
* @author zhangshuaiyin
* @date 2021/12/29 18:20
*/
@Data
public class UserInfoDTO implements Serializable {
private static final long serialVersionUID = 1L;
@NotBlank(message = "{1001}")
private String username;
@NotNull(message = "{1001}")
private Long life;
@NotNull(message = "{1001}")
private Integer age;
@NotEmpty(message = "{1001}")
private List<Long> friendIds;
}
常用注解:
@NotBlank
:用于 String 类型@NotNull
:用于引用类型-
级联校验
@Valid
注解用于级联校验。用法如下: ```java /**- @author zhangshuaiyin
@date 2021/12/29 18:20 */ @Data public class UserInfoDTO implements Serializable { private static final long serialVersionUID = 1L;
@NotEmpty(message = “{1001}”) @Valid private List
friends; }
```java
/**
* @author zhangshuaiyin
* @date 2021/12/29 18:20
*/
@Data
public class Friend implements Serializable {
private static final long serialVersionUID = 1L;
@NotBlank(message = "{1001}")
private String username;
@NotNull(message = "{1001}")
private Long life;
@NotNull(message = "{1001}")
private Integer age;
}