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

时间:2016-01-05 02:04:15

标签: java spring validation annotations

喜欢那个

visible: hidden;

Java bean验证有3个属性:消息,有效负载和组。我想添加一个新的:@NotNull(code=10000) @Size(min=5, max=10, code=10001)

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

1 个答案:

答案 0 :(得分:4)

对你的问题的简短回答:不,你不能只添加额外的字段,也不能使用继承,也可以添加额外的字段。请参阅this question,其中解释了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;
}

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

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

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

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

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

如果多次验证失败,ConstraintValidatorContext可用于构建错误消息。您可以根据需要详细说明,但请注意,此代码可以非常快速地使用。

相关问题