【问题标题】:Is it possible to add custom property to java bean validation annotation?是否可以将自定义属性添加到 java bean 验证注释?
【发布时间】:2016-01-05 02:04:15
【问题描述】:

这样

@NotNull(code=10000)
@Size(min=5, max=10, code=10001)

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。好像不行?

【问题讨论】:

标签: java spring validation annotations


【解决方案1】:

对您的问题的简短回答:不,您不能只添加一个额外的字段,也不能使用继承来添加额外的字段。请参阅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 可用于构建您的错误消息。您可以根据需要进行详细说明,但请注意,此代码可能会很快变成意大利面条。

【讨论】:

    猜你喜欢
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2017-12-18
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多