约束注释中的变量字段

约束注释中的变量字段

本文介绍了约束注释中的变量字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个自定义约束注释,它可以访问我的 bean 的另一个字段的值.我将使用此注释来验证该字段,因为它取决于另一个字段的值,但我定义它的方式编译器说我的字段的注释属性的值"必须是一个常量表达式".

I need to create a custom constraint annotation which can access the value of another field of my bean. I'll use this annotation to validate the field because it depends on the value of the other but the way I define it the compiler says "The value for annotation attribute" of my field "must be a constant expression".

我是这样定义的:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=EqualsFieldValidator.class)
@Documented
public @interface EqualsField {
    public String field();

    String message() default "{com.myCom.annotations.EqualsField.message}";

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

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

public class EqualsFieldValidator implements ConstraintValidator<EqualsField, String>{

    private EqualsField equalsField;

    @Override
    public void initialize(EqualsField equalsField) {
        this.equalsField = equalsField;
    }

    @Override
    public boolean isValid(String thisField, ConstraintValidatorContext arg1) {
        //my validation
    }

}

在我的 bean 中,我想要这样的东西:

and in my bean I want something like this:

public class MyBean{

     private String field1;

     @EqualsField(field=field1)
     private String field2;
}

有没有办法定义注解,让字段值可以是变量?

Is there any way to define the annotation so the field value can be a variable?

谢谢

推荐答案

最简单的做法是退后一步:您编写的约束/验证器适用于字段级别,但您想要强制执行的是跨域依赖,即类级约束.

The easiest thing to do is take one step back: the constraint/validator you have written works on a field-level, but what you want to enforce is a cross-field dependency i.e. a class-level constraint.

重写你的约束和验证器以在类级别工作(即注释将在类上,而不是在字段上).这样你就可以访问整个类.在您的 isValid(..) 方法中,只需对两个字段执行 get、比较并适当返回.

Rewrite your constraint and validator to work at the class level (i.e. the annotation will go on the class, not on the field). That way you'll get access to the entire class. In your isValid(..) method, simply do a get on both the fields, compare, and return appropriately.

这篇关于约束注释中的变量字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 13:13