2013-06-05 50 views
1

在我的场景中,我试图创建注释,该注释验证如果一个字段被填充,如果另一个字段具有某种类型的值。Java jsr 303从注释字段中访问bean字段

界面看起来是这样的:

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

与实现

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

而且用法示例:

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

我用它在Spring MVC和验证对这样的请求:

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

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

我的问题是,如果我可以访问Validation should be here (1)当前豆值?我知道我可以对整个bean进行注释,但我会这样做。

+0

你必须使用一个豆?如果您使用构建器,您可以在'.build()'时间进行这种验证,而无需使用注释。 – fge

+0

你能更具体还是提供一些例子?也许我应该提到,我在Spring MVC中使用它并验证请求是这样的:'public String myFormPostPost(Model model, @Valid @ModelAttribute MyForm form,BindingResult result)' – kamil

+0

那么,你应该提到Spring MVC,是的,并添加相关标签(s?)。我不会做Spring,所以我不知道你是否可以使用它。 – fge

回答