2011-04-05 36 views
2

休眠,我想对Hibernate注释 提供本地化的错误信息,所以我创建的属性文件ValidatorMessages.properties,ValidatorMessages_ar.propertiesHibernate验证和本地化的错误消息?

,并把它们放在资源文件夹中,我使用从为messageSource属性文件阅读:

<bean id="messageSource" 
     class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 
     <property name="basenames"> 
      <list> 
       <value>classpath:messages</value> 
       <value>classpath:errors</value> 
       <value>classpath:app</value> 
       <value>classpath:ValidatorMessages</value> 
      </list> 
     </property> 
     <property name="defaultEncoding" value="UTF-8" /> 
    </bean> 

,并在课堂上,我使用类似:

@NotNull(message = "{validation.notEmpty.password}") 
private string password; 

,并要求验证当我使用:

Validator validator = Validation.buildDefaultValidatorFactory() 
       .getValidator(); 
     Set<ConstraintViolation<MyClass> cvs = validator 
       .validate(myObject); 
     for (ConstraintViolation<MyClass> cv : cvs) { 
      String field = cv.getPropertyPath().toString(); 
      result.addError(new FieldError("version", field, cv.getMessage())); 
     } 

     if (result.hasErrors()) { 
      initModel(); 
      result.reject("add.version.errors"); 
      return "manageVersions"; 
     } 

它正常工作与英语中,它正确地显示英文消息,但切换到阿拉伯语时,它仍显示英文消息,而不是阿拉伯语,虽然

LocaleContextHolder.getLocale()表明语言发生了变化,它的阿拉伯语,那么配置或任何想法可能会导致什么缺失?

回答

2

在当你设置你的验证豆你的Spring配置,我想你需要设置邮件插值:

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> 
    <property name="messageInterpolator" ref="interpolator" /> 
</bean> 

其中插豆将类型LocaleContextMessageInterpolator(见here获取更多信息) 。 Hibernate验证器不会自动知道要查看LocaleContextHolder。

您可能还需要设置validationMessageSource属性,但我认为它的默认设置正确,因为您至少收到了英文错误消息。

+0

我想这个答案更合适 - http://stackoverflow.com/questions/11225023/messageinterpolator-in-spring#11226683。 – Gedrox 2013-02-07 13:42:41