2011-06-09 38 views
1

我正在使用Hibernate驗證器。我有一個類級別的註釋。它比較三個性質的平等。當執行驗證時,我需要從返回的javax.validation.ConstraintViolation對象中獲取PropertyPath。由於它不是單個字段,因此getPropertyPath()方法返回null。是否有另一種方法來查找PropertyPaths?如何從類級別註釋衝突獲得屬性路徑

這是我的註釋實現 -

@MatchField.List({ 
@MatchField(firstField = "firstAnswer", secondField = "secondAnswer", thirdField = "thirdAnswer"), 
}) 

回答

2

你需要設置信息映射到當你確認,你想拒絕的屬性。 Hibernate驗證器沒有辦法自動地魔法確定自定義註釋屬性是屬性路徑。

public class MatchFieldValidator implements ConstraintValidator<MatchField, Object> { 

    private MatchField matchField; 

    @Override 
    public void initialize(MatchField matchField) { 
    this.matchField = matchField; 
    } 

    @Override 
    public boolean isValid(Object obj, ConstraintValidatorContext cvc) { 

    //do whatever you do 
    if (validationFails) { 
     cvc.buildConstraintViolationWithTemplate("YOUR FIRST ANSWER INPUT IS WRONG!!!"). 
         addNode(matchField.firstAnswer()).addConstraintViolation(); 
     cvc.buildConstraintViolationWithTemplate("YOUR SECOND ANSWER INPUT IS WRONG!!!"). 
         addNode(matchField.secondAnswer()).addConstraintViolation(); 
     //you get the idea 
     cvc.disableDefaultConstraintViolation(); 
     return false; 
    } 
    } 
}