org.hibernate.validator.constraints.Email消息i18n

时间:2014-01-17 07:54:52

标签: java hibernate internationalization validation

@NotBlank(message = "Email is required!")
@Email(message = "Please add a correct email address!")
@Column(name = "EMAIL", unique = true, nullable = false)
private String email;

我正在使用hibernate验证来检查有效的电子邮件地址。

如何将验证消息国际化?

1 个答案:

答案 0 :(得分:0)

您可以使用LocalValidatorFactoryBean:

LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
factory.setValidationMessageSource( // initialize a ResourceBundleMessageSource  );
factory.afterPropertiesSet();

可以像这样使用ResourceBundleMessageSource:

ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages/messages");
messageSource.setDefaultEncoding("UTF-8");

对于I18N文件:/../src/messages/messages.properties(默认)和/.../src/messages/messages_nl_BE.properties和...

然后将您的工厂放在BeanValidationEventListener中并注册BeanValidationEventListener

BeanValidationEventListener beanValidationEventListener = new BeanValidationEventListener(factory, new Properties());
HibernateConfig.register(sessionFactory, EventType.PRE_INSERT, beanValidationEventListener);
HibernateConfig.register(sessionFactory, EventType.PRE_UPDATE, beanValidationEventListener);

这样的事情应该有效。 (你必须弄清楚细节。)


在xml配置中的OR:

<!-- The LocalValidatorFactoryBean is able to instantiate custom validators and inject autowired dependencies. -->
<bean id="validator"
  class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

<!--
  This is the key to link Spring's injection to Hibernate event-based validation.
  Notice the first constructor argument, this is our Spring ValidatorFactory instance.
 -->
<bean id="beanValidationEventListener" class="org.hibernate.cfg.beanvalidation.BeanValidationEventListener">
    <constructor-arg ref="validator"/>
    <constructor-arg ref="hibernateProperties"/>
</bean>

<bean id="mySessionFactory"   class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
...

  <!--
    A reference to our custom BeanValidationEventListener instance is pushed for all events.
    This can of course be customized if you only need a specific event to trigger validations.
   -->
  <property name="eventListeners">
      <map>
          <entry key="pre-update" value-ref="beanValidationEventListener"/>
          <entry key="pre-insert" value-ref="beanValidationEventListener"/>
          <entry key="pre-delete" value-ref="beanValidationEventListener"/>
      </map>
  </property>
</bean>

默认情况下,从名为“ValidationMessages”的资源包中检索消息。因此,只需为您需要的语言提供此捆绑包(例如ValidationMessages.properties),以覆盖来自Hibernate Validator的默认消息(从包“org.hibernate.validator.ValidationMessages.properties”中检索)。

https://docs.jboss.org/hibernate/validator/4.0.1/reference/en/html/validator-usingvalidator.html#section-message-interpolation