1
我正在使用下面的類來驗證我的bean與Hibernate驗證。它效果很好。它基本上是爲JPA 1發現的here的偵聽器,轉換爲用於在我的Spring控制器中驗證bean。我試圖自定義返回的消息。 This以及我可以找到的每個其他資源,只需在Web-Inf目錄中放置一個ValidationMessages.properties文件即可。這個文件也包含在下面。這不起作用。有什麼建議麼?是否有任何配置需要使用休眠驗證自定義消息
public class BeanValidationTool {
public void validate(Object entity) {
TraversableResolver tr = new MyTraversableResolver();
Validator validator = Validation.buildDefaultValidatorFactory().usingContext().traversableResolver(tr).getValidator();
final Set<ConstraintViolation<Object>> constraintViolations = validator.validate(entity);
if (constraintViolations.size() > 0) {
Set<ConstraintViolation<?>> propagatedViolations = new HashSet<ConstraintViolation<?>>(constraintViolations.size());
Set<String> classNames = new HashSet<String>();
for (ConstraintViolation<?> violation : constraintViolations) {
propagatedViolations.add(violation);
classNames.add(violation.getLeafBean().getClass().getName());
}
StringBuilder builder = new StringBuilder();
builder.append("validation failed for classes ");
builder.append(classNames);
throw new ConstraintViolationException(builder.toString(), propagatedViolations);
}
}
public class MyTraversableResolver implements TraversableResolver {
public boolean isReachable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
return traversableObject == null || Hibernate.isInitialized(traversableObject);
}
public boolean isCascadable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
return true;
}
}
}`
ValidationMessages.properties文件
validator.min = must be greater than or equal to {value}
validator.notEmpty = This field can't be empty
這是如何在春季設置自定義的消息有很大的描述,但是,也許我的理解是有限的,我認爲,爲了專門定製Hibernate Validator消息,我不應該使用bean。而應該自動替換這些值,並在調用validate方法時返回。 – coder 2011-01-10 21:01:01