是否可以向 java bean 验证注释添加自定义属性?

wwu*_*ric 3 java validation spring annotations

像那样

@NotNull(code=10000)
@Size(min=5, max=10, code=10001)
Run Code Online (Sandbox Code Playgroud)

Java bean 验证有 3 个属性:消息、有效负载和组。我想添加一个新的:code.

我检查了一些文档,例如https://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html/validator-customconstraints.htmlhttps://docs.oracle.com/javaee/ 6/tutorial/doc/gkfgx.html。好像不可能吧?

Jam*_*ENL 5

对您的问题的简短回答:不,您不能只添加额外的字段,也不能使用继承来添加额外的字段。看到这个问题,它解释了为什么 Java 不允许使用注释进行继承。

您所要做的就是创建您自己的特定版本的注释@Size。但是您应该能够将@Size注释应用到您的自定义注释中,以便@Size在运行验证时自动检查。

您的注释可能如下所示:

@Constraint(validatedBy = { })
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
//The only downside of this approach 
//is that you have to hardcode your min and max values
@Size(min=5, max=10)
public @interface CodedSize {
    String message() default "{Default Validation Message}";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };
    int code() default 0;
}
Run Code Online (Sandbox Code Playgroud)

如果您想在注释中指定大小,您可以这样做,并编写一个自定义验证器来验证您的注释。

@Constraint(validatedBy = { CodedSizeValidator.class })
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface CodedSize {
    String message() default "{Default Validation Message}";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };
    int minSize() default 5;
    int maxSize() default 10;
    int code() default 0;
}
Run Code Online (Sandbox Code Playgroud)

然后你的自定义验证器看起来像这样:

public class CodedSizeValidator implements ConstraintValidator<CodedSize, String> {

    private int minSize;
    private int maxSize;
    private int code;

    @Override
    public void initialize(CodedSize constraintAnnotation){
        this.minSize = constraintAnnotation.minSize();
        this.maxSize = constraintAnnotation.maxSize();
        this.code = constraintAnnotation.code();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        boolean isValid = false;
        if(value == null || value.isEmpty()) {
            //if a null or empty value is valid, then set it here.
            isValid = true;   
        } else {
            //Logic here to determine if your value is valid by size constraints.
        }
        return isValid;
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用它是String因为这似乎最适用,但你可以轻松使用Number,甚至是一种泛型类型,以允许您在多个字段上使用此注释。这样做的好处是,如果您想通过此验证添加空检查,您可以这样做。

如果多次验证失败,可以使用它ConstraintValidatorContext来构建错误消息。您可以根据需要将其详细化,但请注意,此代码可能会很快变得像意大利面条一样。