【问题标题】:Use Spring ressource bundle with Hibernate Validator将 Spring 资源包与 Hibernate Validator 一起使用
【发布时间】:2014-11-27 15:34:10
【问题描述】:

第一次在这里发帖。

我正在开发一个 JSON 网络服务 API,我正在尝试使用自定义验证消息,但没有成功。

这是我的设置(关注与我的问题有关的组件。我还使用 MyBatis、jUnit...):

  • Tomcat 8.0.14
  • 春季 4.1.1
  • 球衣 2.13
  • Jersey-spring3 2.13
  • 泽西豆验证
  • 休眠验证器 5.0.0.Final

Bean 属性验证和类级验证工作正常。 现在我正在尝试设置自定义错误验证消息。

我不想使用 JSR-303 /META-INF/ValidationMessages.properties,但我不想使用 spring 托管包。

在我的 applicationContext.xml 中,我定义了:

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

<bean name="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="configuration/messages/validation" />
</bean>

我还创建了一个带有一些属性的 /WEB-INF/classes/configuration/messages/validation_fr_FR.properties :

model.error=Modèle invalide

现在,当我尝试验证我的 Bean 时,我在日志中得到了这个:

15:47:14,300 DEBUG http-nio-8080-exec-2 resourceloading.PlatformResourceBundleLocator:72 - ValidationMessages not found.
15:47:45,707 DEBUG http-nio-8080-exec-2 resourceloading.PlatformResourceBundleLocator:69 - org.hibernate.validator.ValidationMessages found.

这里没有提到我的捆绑包...

在我的 JSON 响应中,我得到:

{model.error} (path = EventServiceAPIImpl.createOrUpdateEvent.arg0, invalidValue = fr.bz.pdcv.bean.Event@d99af88)

{model.error} 没有替换为我的自定义消息。

我认为我的 ReloadableResourceBundleMessageSource 被 Hibernate Validator 默认配置覆盖。但为什么呢?

我重载了 google 和 stackoverflow 来寻找解决方案,但我没有找到任何可以帮助我的东西

有人遇到同样的问题吗?

谢谢!

【问题讨论】:

  • 我来迟了你的问题。但最有可能的问题是您无法告诉 Hibernate Validator 您的 Locale 是什么。此外,休眠验证器默认使用 en_US 语言环境。所以很可能休眠验证器无法找到与默认语言环境相关的validationMessage,因此您会看到错误。

标签: java spring validation hibernate-validator tomcat8


【解决方案1】:

虽然我想我迟到了,但它可能对其他人有所帮助。

ValidationMessages.properties 文件重命名您的 validation_fr_FR.properties,并将其放在文件夹“src\main\resources”中。 p>

所以你的最终路径如下:

src\main\resources\ValidationMessages.properties

重新启动服务器并尝试呈现验证。

你不再需要 LocalValidatorFactoryBeanResourceBundleMessageSource

Hibernate 基本上是在默认目录中寻找相同的文件名并覆盖默认的ValidationMessages.properties

【讨论】:

    猜你喜欢
    • 2011-10-16
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    • 2015-12-26
    • 2014-04-06
    相关资源
    最近更新 更多