hibernate验证和本地化错误消息?
问题内容:
hibernate状态,我想为hibernate注释提供本地化的错误消息,因此我创建了属性文件ValidatorMessages.properties,ValidatorMessages_ar.properties
并将它们放在资源文件夹中,我正在使用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()
表示语言已更改并且是阿拉伯语,那么配置中是否缺少某些内容或任何想法可能导致该错误?
问题答案:
在设置验证器bean的Spring配置中,我认为您需要设置消息插值器:
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="messageInterpolator" ref="interpolator" />
</bean>
插值器bean的类型为LocaleContextMessageInterpolator(有关更多信息,请参见此处)。Hibernate
Validator不会自动知道要查看LocaleContextHolder。
您可能还需要设置validationMessageSource属性,但我认为它的默认设置正确,因为至少您会收到英语错误消息。