简体   繁体   English

Java jsr 303从带注释的字段访问bean字段

[英]Java jsr 303 accessing bean fields from annotated field

In my scenario I'm trying to create annotation that validates if one field is filled if another one has some kind of value. 在我的场景中,我试图创建注释,以验证如果另一个字段具有某种值,是否填充了一个字段。

The interface looks like this: 该界面如下所示:

@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = RequiredIfFieldHasValueValidator.class)
public @interface RequiredIfFieldHasValue
{
    String message() default "Required if selected";

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

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

    /*
    FieldName against which we validate
     */
    String fieldName() default "";

    /*
    Field value that indicates requirement
     */
    String fieldValue() default "";
} 

And implementation: 并实现:

public class RequiredIfFieldHasValueValidator implements ConstraintValidator<RequiredIfFieldHasValue, String>
{
    private String fieldName;
    private String fieldValue;

    @Override
    public void initialize( RequiredIfFieldHasValue constraintAnnotation )
    {
        fieldName = constraintAnnotation.fieldName();
        fieldValue = constraintAnnotation.fieldValue();
        validateParameters();
    }

    @Override
    public boolean isValid( String value, ConstraintValidatorContext context )
    {
        System.out.println( "Validate against fieldname: " + fieldName + " fieldvalue: " + fieldValue );
        //
        //Validation should be here (1)
        //
        return false;
    }

    private void validateParameters()
    {
        if ( "".equals( fieldName ) || fieldName == null )
        {
            throw new IllegalArgumentException( "The fieldname cannot be null" );
        }
    }
}

And example usage: 用法示例:

public class Form {
    private String type;
    @RequiredIfFieldHasValue(fieldName = "type", fieldValue = "DICT")
    private String dictValue;
}

I use it in Spring MVC and validate on request like this: 我在Spring MVC中使用它,并按要求进行验证,如下所示:

public String myFormPostPost( Model model, @Valid @ModelAttribute MyForm form, indingResult result )

So my goal is: If field type has value equal to DICT, field dictValue should be required (not empty) . 所以我的目标是: If field type has value equal to DICT, field dictValue should be required (not empty)

My question is if I can access current bean values in Validation should be here (1) ? 我的问题是,是否可以在Validation should be here (1)访问当前的bean值Validation should be here (1) I know I could do annotation to whole bean, but I'd prefere it that way. 我知道我可以对整个bean进行注释,但是我更喜欢这样。

好吧,我想这是不可能的,所以我坚持使用带类注释的解决方案: 使用Hibernate Validator(JSR 303)进行跨字段验证

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM