gpt4 book ai didi

spring - Spring 中的 MessageInterpolator

转载 作者:行者123 更新时间:2023-12-04 16:40:29 24 4
gpt4 key购买 nike

我使用 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

有任何想法吗?

最佳答案

您不必申报 ResourceBundleMessageInterpolatorMessageSourceResourceBundleLocator bean 由您自己创建(除非您必须这样做),它们是由 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">例如。

关于spring - Spring 中的 MessageInterpolator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11225023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com