依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-validation</artifactId>
  4. </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;
}

常用注解:

  1. @NotBlank:用于 String 类型
  2. @NotNull:用于引用类型
  3. @NotEmpty:用于集合、数组类型

    级联校验

    @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;
}