在Hibernate + Spring中使用自定义验证消息

时间:2012-02-10 17:43:50

标签: hibernate spring spring-3 hibernate-validator

我尝试了答案中的步骤:Hibernate Validator, custom ResourceBundleLocator and Spring

但仍然只是将{location.title.notEmpty}作为输出而不是消息。

调度-servlet.xml中

<bean name="validator"
    class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="validationMessageSource">
        <ref bean="resourceBundleLocator"/>
    </property>
</bean>

<bean name="resourceBundleLocator" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>/WEB-INF/validationMessages</value>
        </list>
    </property>
</bean>

/WEB-INF/validationMessages.properties:

location.title.notEmpty=My custom message

表格(班级位置)

@NotEmpty( message = "{location.title.notEmpty}" )
private String title;

这里出了什么问题?

1 个答案:

答案 0 :(得分:13)

知道了! : - )

我将以下bean添加到我的dispatcher-servlet.xml

中,而不是上面提到的两个
  <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/validationMessages" />
  </bean>

然后,在我的validationMessages.properties中,我使用了以下语法:

NotEmpty.location.title=My custom Message

我想这就是原因:我使用了Hibernate验证注释(而不是javax注释)

一般来说,消息文件的语法应该是

[ConstraintName].[ClassName].[FieldName]=[Message]

希望这可以帮助其他人; - )

要从spring控制器访问消息,只需将@Autowired private MessageSource messageSource;添加为类字段并使用messageSource.getMessage方法。因为我只使用一个区域设置,所以我使用了messageSource.getMessage( "NotEmpty.location.title", null, null )

相关问题