2

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()表示语言已更改并且是阿拉伯语,因此配置是否缺少某些内容或任何可能导致该问题的想法?

4

1 回答 1

2

在设置验证器 bean 时,在 Spring 配置中,我认为您需要设置消息插值器:

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

其中插值器 bean 的类型为 LocaleContextMessageInterpolator(有关更多信息,请参见此处)。Hibernate Validator 不会自动知道要查看 LocaleContextHolder。

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

于 2011-05-07T00:17:52.543 回答