@NotBlank(message = "Email is required!")
@Email(message = "Please add a correct email address!")
@Column(name = "EMAIL", unique = true, nullable = false)
private String email;
我正在使用 hibernate 验证来检查有效的电子邮件地址。
如何国际化验证消息?
最佳答案
您可以使用 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 配置中:
<!-- 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”的资源包中检索的。因此,只需为您需要覆盖 Hibernate Validator 的默认消息(从“org.hibernate.validator.ValidationMessages.properties”包中检索)的语言提供此包(例如 ValidationMessages.properties)即可。
关于java - org.hibernate.validator.constraints.电子邮件消息 i18n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21180607/