在约束注释变量字段 [英] Variable field in a constraint annotation

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

问题描述

我需要创建一个定制约束注释可以访问我的bean的另一个字段的值。我将使用此批注来验证字段,因为这取决于其他的价值,但我定义的方式编译器说:该值标注属性我的领域中必须是一个常数前pression。

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
    }

}

在我的豆我想是这样的:

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(..)方法,只需做既拿到领域,比较,并适当回报。

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆