2010-07-30 90 views
2

我试图使用MessageSource检索默认验证错误消息。我正在使用的代码使用反射来检索message参数的值。在不覆盖message参数的约束条件下,我想检索默认的错误消息。当我在验证注释上调用message方法时,我得到{org.hibernate.validator.constraints.NotBlank.message}(例如,对于@NotBlank注释)。然后,我试图用MessageSource得到错误信息,像这样:如何从Hibernate Validator检索默认验证消息?

String message = messageSource.getMessage(key, null, Locale.US); 

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

UPDATE

澄清。我的印象是,Spring的默认配置文件是message.properties。我在这个假设中纠正了吗?

UPDATE

更改名称问题,以更好地反映什么,我要怎样做。

+0

肯定有自动生成的消息对于某些违反约束,但我不认为它表示为'messages.properties'文件。 – skaffman 2010-07-30 15:10:24

+0

@skaffman你知道spring/hibernate-validator从哪里得到这些消息吗? – 2010-07-30 15:14:52

+0

'fraid不,不。我很确定它是Hibernate Validator,但它不是Spring。 – skaffman 2010-07-30 15:27:44

回答

1

从Hibernate的球员之一运行到一个blog post后,并在Hibernate验证源周围挖掘后,我想我已经想通了:

public String getMessage(Locale locale, String key) { 
    String message = key; 
    key = key.toString().replace("{", "").replace("}", ""); 

    PlatformResourceBundleLocator bundleLocator = new PlatformResourceBundleLocator(ResourceBundleMessageInterpolator.DEFAULT_VALIDATION_MESSAGES); 
    ResourceBundle resourceBundle = bundleLocator.getResourceBundle(locale); 

    try { 
     message = ResourceBundle.getString(key); 
    } 

    catch(MissingResourceException) { 
     message = key; 
    } 

    return message; 
} 

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

UPDATE

另一个(容易)的方法是更新您的applicationContext.xml并做到这一点:

<bean id="resourceBundleSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 
    <property name="basenames"> 
     <list> 
      <value>org.hibernate.validator.ValidationMessages</value> 
     </list> 
    </property> 
</bean> 

现在你MessageSource被填入默认的邮件,你可以做messageSource.getMessage()。事实上,这可能是最好的方法。