如何从 Hibernate Validator 检索默认验证消息?

Viv*_*ath 7 java validation spring

我正在尝试使用 检索默认验证错误消息MessageSource。我正在使用的代码使用反射来检索message参数的值。对于不覆盖message参数的约束,我想检索默认错误消息。当我调用message验证注释上的方法时,我得到{org.hibernate.validator.constraints.NotBlank.message}(例如,对于@NotBlank注释)。然后我尝试使用MessageSource来获取错误消息,如下所示:

String message = messageSource.getMessage(key, null, Locale.US);
Run Code Online (Sandbox Code Playgroud)

我尝试设置key{org.hibernate.validator.constraints.NotBlank.message}, org.hibernate.validator.constraints.NotBlank.message(去掉大括号),甚至org.hibernate.validator.constraints.NotBlank但我不断得到null. 我在这里做错了什么?

更新

一个澄清。我的印象是 Springmessage.properties为其约束提供了一个默认文件。我的这个假设正确吗?

更新

更改问题的名称以更好地反映我想要做的事情。

Viv*_*ath 6

在阅读了一位 Hibernate 人员的博客文章并深入研究了 Hibernate Validator 源代码之后,我想我已经弄清楚了:

public String getMessage(final Locale locale, final String key) {
    PlatformResourceBundleLocator bundleLocator = new PlatformResourceBundleLocator("org.hibernate.validator.ValidationMessages");
    ResourceBundle resourceBundle = bundleLocator.getResourceBundle(locale);

    try {
       final String k = key.replace("{", "").replace("}", "");
       return resourceBundle.getString(k);
    }
    catch (MissingResourceException e) {
       return key;
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,首先,您必须PlatformResourceBundleLocator使用默认验证消息实例化 a 。然后,您从定位器中检索ResourceBundle并使用它来获取消息。但我不相信这会执行任何插值。为此,您必须使用插值器;我上面链接的博客文章对此进行了更详细的介绍。

更新

另一种(更简单)的方法是更新您的applicationContext.xml并执行以下操作:

<bean id="resourceBundleSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>org.hibernate.validator.ValidationMessages</value>
        </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

现在您MessageSource已填充默认消息,您可以执行以下操作messageSource.getMessage()。事实上,这可能是最好的方法。