2010-07-30 88 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()。事實上,這可能是最好的方法。