【问题标题】:How to inject values from another properties file into ValidationMessages.properties?如何将另一个属性文件中的值注入 ValidationMessages.properties?
【发布时间】:2015-03-29 07:52:50
【问题描述】:

我需要更改 hibernate-validator 使用的 @NotNull 消息。

已使用 ValidationMessages.properties 中的一行成功完成此操作,例如:javax.validation.constraints.NotNull.message=my validation message

但是,这并不是我们所需要的。将省略有关原因的详细信息,但所有这些消息都应源自单个 messages.properties 文件,其目的不仅用于验证,还用于其他消息。

假设messages.properties 最初包含一个属性CCCI_0001=my generic message。是否可以以某种方式将此属性值从 messages.properties 替换为 ValidationMessages.properties 中的占位符?

【问题讨论】:

  • 不,抱歉,所有的 Hibernate 验证消息都必须在注解中声明,并且不能使用 @Value 注解动态注入。您也许可以编写一个自定义注释包装器,允许您将值注入错误消息中,但默认情况下它们不能是动态的

标签: java spring hibernate hibernate-validator properties-file


【解决方案1】:

您可以做的是使用自定义 MessageInterpolator 引导您的 ValidatorFactory。如果您乐于使用 Hibernate Validator 特定功能,您可以使用ResourceBundleLocator - 请参阅http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-custom-message-interpolation。它看起来有点像这样:

Validator validator = Validation.byDefaultProvider()
        .configure()
        .messageInterpolator(
                new ResourceBundleMessageInterpolator(
                        new PlatformResourceBundleLocator( "MyMessages" )
                )
        )
        .buildValidatorFactory()
        .getValidator();

【讨论】:

    猜你喜欢
    • 2017-06-18
    • 2017-12-12
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 2019-08-03
    • 2016-06-06
    • 2016-10-16
    • 2013-07-23
    相关资源
    最近更新 更多