2011-01-06 62 views
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 

回答

1

你在你的應用上下文中定義爲messageSource:

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" abstract="false" 
     scope="singleton" lazy-init="default"> 
    <property name="basename" value="ValidationMessages"/> 
</bean> 

比你只需要使用bean來獲取信息:

@Autowired 
private MessageSource messageSource; 

public String getMessage(String messageName) { 
    return messageSource.getMessage(messageName, null, null); 
} 

爲了訪問上下文中的豆你將不得不這樣做還有:

@Component 
public class BeanValidationTool{... 
+0

這是如何在春季設置自定義的消息有很大的描述,但是,也許我的理解是有限的,我認爲,爲了專門定製Hibernate Validator消息,我不應該使用bean。而應該自動替換這些值,並在調用validate方法時返回。 – coder 2011-01-10 21:01:01