2012-11-29 40 views
3

如果我有ConstraintValidatorContext,並且我正在使用buildConstraintViolationWithTemplate(String messageTemplate)構建ConstraintViolationContextBuilder,是否有任何可能性來傳遞自定義參數值?JSR 303/ConstraintValidatorContext:參數化錯誤消息

相應的屬性文件看起來在某種程度上是這樣的:

Foobar.invalidValue.message=Invalid value. Valid values are {VALID_VALUES} 

然後我想以編程方式設置值{VALID_VALUES}

你有什麼想法嗎?

回答

3

您只能在消息模板中引用相關約束註釋的屬性,例如,像這樣與屬性minmax約束:

size must be between {min} and {max} 

所以,你可以作爲註解屬性指定有效值。

如果你使用Hibernate驗證作爲Bean驗證提供者,你可能實現自定義ResourceBundleLocator它會返回鍵束爲你的價值觀:

public class MyResourceBundleLocator implements ResourceBundleLocator { 

    public ResourceBundle getResourceBundle(Locale locale) { 
     //return a bundle with keys for your values, e.g. set dynamically 
    } 
} 

然後獲得驗證時所設置的定位:

Validator validator Validation.byProvider(HibernateValidator.class) 
    .configure() 
    .messageInterpolator(
     new ResourceBundleMessageInterpolator(
      new MyResourceBundleLocator())) 
    .buildValidatorFactory() 
    .getValidator(); 

或者,你可以自己格式化和準備消息,並將其傳遞給buildConstraintViolationWithTemplate()

+0

非常感謝您對這個解釋廣泛:)! – parkerlewis