5

我使用 Spring 3.1.1 和 Hibernate-validator 4.3.0.Final 并且在更改默认 MessageInterpolator 时遇到问题,它从 ValidationMessages(在类路径中)获取验证消息。

我想使用 ResourceBundleMessageInterpolator 从我的 spring messageSource 中获取消息

我在 application-context.xml 中做了这样的事情:

<bean id="resourceBundleMessageInterpolator"
      class="org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator">
    <constructor-arg index="0">
        <bean class="org.springframework.validation.beanvalidation.MessageSourceResourceBundleLocator">
            <constructor-arg index="0" ref="messageSource"/>
        </bean>
    </constructor-arg>
</bean>
<bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="messageInterpolator" ref="resourceBundleMessageInterpolator"/>
</bean>

当我在日志中启动我的 Web 应用程序时,我看到:

11:04:07,402 DEBUG [org.hibernate.validator.internal.engine.ConfigurationImpl] - 
Setting custom MessageInterpolator of type
 org.springframework.validation.beanvalidation.LocaleContextMessageInterpolator 
11:04:07,402 DEBUG [org.hibernate.validator.internal.engine.ConfigurationImpl] - 
Setting custom ConstraintValidatorFactory of type org.springframework .validation.beanvalidation.SpringConstraintValidatorFactory

如您所见,这不是我想要的 ResourceBundleMessageInterpolator。这是 LocaleContextMessageInterpolator

后来,当我尝试验证某些内容时,我只是从 ValidationMessages.properties 中获取消息,而不是从 spring 消息源中获取消息:

11:08:09,397 DEBUG [org.hibernate.validator.resourceloading.PlatformResourceBundleLocator] - 
ValidationMessages not found.
11:08:09,413 DEBUG [org.hibernate.validator.resourceloading.PlatformResourceBundleLocator] - 
org.hibernate.validator.ValidationMessages found.

从application-context.xml可以看到我想用MessageSourceResourceBundleLocator,但是用了,不知道为什么是PlatformResourceBundleLocator

有任何想法吗?

4

1 回答 1

15

您不必自己声明ResourceBundleMessageInterpolatorMessageSourceResourceBundleLocatorbean(除非您必须),它们是LocalValidatorFactoryBean在您提供时创建的messageSource

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

(它在引擎盖下做到了这一点:)

public void setValidationMessageSource(MessageSource messageSource) {
    this.messageInterpolator = HibernateValidatorDelegate.buildMessageInterpolator(messageSource);
}

// (...)


private static class HibernateValidatorDelegate {

    public static MessageInterpolator buildMessageInterpolator(MessageSource messageSource) {
        return new ResourceBundleMessageInterpolator(new MessageSourceResourceBundleLocator(messageSource));
    }
}

那么通过简化的 bean 定义,你会得到相同的调试输出吗?您在哪里使用“验证器”参考?例如,您可能必须使用<mvc:annotation-driven validator="validator">

于 2012-06-27T12:54:30.950 回答