Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker DevOps


Spring Boot 使用 Validated group 分组校验

Spring Boot 大约 1536 字

group

@Validjavax中的注解,它有一个group字段,但javax没有实现分组校验。

Spring Validation实现了这个功能,配合@Validated注解可以实现:同一个请求对象,同一份校验注解,不同接口,不同的校验逻辑。

  • /basic:只校验BasicInfogroup
  • /advance:只校验AdvanceInfogroup
  • /combine:只校验Combinegroup。(Combine上定义了@GroupSequence,表示:校验的顺序,也可起到同时校验的作用)
@PostMapping("/basic")
public String basic(@Validated(BasicInfo.class) @RequestBody Signup req) {
    System.out.println("basic#" + req.toString());
    return req.toString();
}

@PostMapping("/advance")
public String advance(@Validated(AdvanceInfo.class) @RequestBody Signup req) {
    System.out.println("advance#" + req.toString());
    return req.toString();
}

@PostMapping("/combine")
public String combine(@Validated(Combine.class) @RequestBody Signup req) {
    System.out.println("combine#" + req.toString());
    return req.toString();
}

namephonecaptcha字段是BasicInfo需要校验的。

captchaaddress字段是AdvanceInfo需要校验的。

Combine接口上定义的@GroupSequence的作用:校验的顺序,也可起到同时校验的作用;这处表示先检验BasicInfo,再校验AdvanceInfo,且需要同时满足BasicInfoAdvanceInfo校验条件。

@Data
public class Signup {

    @NotBlank(groups = BasicInfo.class)
    private String name;

    @NotBlank(groups = BasicInfo.class)
    private String phone;

    @NotBlank(groups = {BasicInfo.class, AdvanceInfo.class})
    private String captcha;

    @NotBlank(groups = AdvanceInfo.class)
    private String address;

    public interface BasicInfo {}

    public interface AdvanceInfo {}

    @GroupSequence({BasicInfo.class, AdvanceInfo.class})
    public interface Combine {}

}

参考

https://www.baeldung.com/javax-validation-groups

阅读 163 · 发布于 2022-10-07

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批