【问题标题】:Use custom validation messages in Hibernate + Spring在 Hibernate + Spring 中使用自定义验证消息
【发布时间】:2012-03-03 04:30:56
【问题描述】:

我在这里尝试了答案中的步骤: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;

这里出了什么问题?

【问题讨论】:

  • 我不知道这是否会导致该问题,但请确保消息属性文件的最后一行有一个空行。
  • 不,这不是问题,不需要最后一个空行

标签: hibernate spring spring-3 hibernate-validator


【解决方案1】:

知道了! :-)

我在dispatcher-servlet.xml 中添加了以下 bean,而不是上面提到的两个:

  <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]

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

要从弹簧控制器访问消息,只需将@Autowired private MessageSource messageSource; 添加为类字段并使用messageSource.getMessage 方法。因为我只使用一种语言环境,所以我使用了messageSource.getMessage( "NotEmpty.location.title", null, null )

【讨论】:

  • 很好,但它也适用于 Hibernate 验证注释 :)
  • 是的,我的第一个想法是它只适用于 hibernate 验证注释,但它适用于 hibernate 和 javax。
  • 中指定验证器时不需要调整语法,见stackoverflow.com/a/21508937/1672678stackoverflow.com/a/22655303/1672678
  • 如果您使用的是 Spring Boot,您可以通过将以下键添加到 application.properties 来利用自动配置:spring.messages.basename=your/basename/messages
猜你喜欢
  • 2019-04-21
  • 1970-01-01
  • 1970-01-01
  • 2016-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
  • 2011-05-01
相关资源
最近更新 更多