Spring注解方法目的

我为 spring 项目编写了简单的验证注释。问题是我不明白某些方法的目的。这是我的注释:


@Constraint(validatedBy = PostCodeValidator.class)

@Target({ElementType.METHOD, ElementType.FIELD})

@Retention(RetentionPolicy.RUNTIME)

public @interface PostCode {

    public String value() default "LUV";

    public String message() default "must start with LUV";

    public Class<?>[] groups() default {};

    public Class<? extends Payload>[] payload() default {};


}

谁能解释我groups()和payload()方法的目的?如果解释尽可能简单,我将不胜感激。谢谢。


FFIVE
浏览 101回答 1
1回答

江户川乱折腾

1) 在Bean Validation Api 中,组用于选择bean 的哪些字段将被验证。示例:具有地址属性的用户。public class User {&nbsp; &nbsp; @NotNull(groups = GroupUser.class)&nbsp; &nbsp; String firstname;&nbsp; &nbsp; @NotNull(groups = GroupAddress.class)&nbsp; &nbsp; String street;&nbsp; &nbsp; @NotNull(groups = GroupAddress.class)&nbsp; &nbsp; String city;}要验证整个用户,您可以执行以下操作:Set<ConstraintViolation<User>> constraintViolations = validator.validate(user, GroupUser.class, GroupAddress.class);要仅验证没有地址部分的用户信息,您可以使用:Set<ConstraintViolation<User>> constraintViolations = validator.validate(user, GroupUserName.class);2) 有效载荷用于管理错误的严重程度。您可以实现 Payload 接口:public class Severity {&nbsp; &nbsp; public static class Info implements Payload {}&nbsp; &nbsp; public static class Error implements Payload {}}如果您使用以下方式注释名字字段:@NotNull(payload = {Severity.Error.class})然后在验证之后,您可以按严重性添加一些逻辑:for (ConstraintViolation<TestBean> violation : constraintViolations) {&nbsp; &nbsp; Set<Class<? extends Payload>> payloads = violation.getConstraintDescriptor().getPayload();&nbsp; &nbsp; for (Class<? extends Payload> payload : payloads) {&nbsp; &nbsp; &nbsp; &nbsp; if (payload == Severity.Error.class) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // logic here&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java