Spring Boot 使用 Validated group 分组校验

Spring Boot About 1,536 words

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

Views: 2,455 · Posted: 2022-10-06

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

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

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


Today On History
Browsing Refresh