2015-04-02 66 views
1

我用Spring4 + Hibernate5 Validator來做驗證。爲什麼使用Hibernate Validator的Spring Message Interpolation參數替換不起作用?

我不想使用默認ValidateMessage.properties,所以我在classpath根目錄下的國際化目錄下定義自己的消息屬性, 的配置信息如下:

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 
    <property name="basenames" value="I18N.messages,I18N.validation.ValidationMessages" /> 
    <property name="defaultEncoding" value="UTF-8" /> 
    <!-- Set whether to use the message code as default message instead of throwing a NoSuchMessageException. 
     Useful for development and debugging. 
     Default is "false".--> 
    <property name="useCodeAsDefaultMessage" value="true"/> 
    <!-- The key here is fallbackToSystemLocale which prevents the system to look into the system, 
     thus using "message.properties" if he doesn't find the locale. --> 
    <property name="fallbackToSystemLocale" value="false"/> 
</bean> 

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

<mvc:annotation-driven validator="validator"/> 

Bean驗證信息是:

@Size(
     min = 2, 
     max = 14, 
     message = "The license plate must be between {min} and {max} characters long" 
) 

我在Spring應用程序中使用這種表示法,但這些參數不被替換。我回來了「牌照必須在最小和最大字符之間」。

Spring Message Interpolation Argument Replacement using Hibernate Validator

我不知道爲什麼它不工作,任何人都可以幫助解決這個問題?謝謝。

回答

2

我找到原因。它是由屬性「useCodeAsDefaultMessage」引起的,我們不能將它設置爲「true」,只是使用默認值「false」。看來如果它是真的,只需從屬性文件中的「basenames」中獲取消息,並且不要在類路徑根路徑或「org/hibernate/validator」中使用默認消息文件!

+0

同意,檢查該方法的API,推薦用於開發。默認情況下是false,所以你可以刪除該行。 – 2015-09-18 16:47:27

相關問題