【问题标题】:Spring Boot JSR303 message code in annotation getting ignored注释中的 Spring Boot JSR303 消息代码被忽略
【发布时间】:2015-04-14 02:11:39
【问题描述】:

在我的 Spring Boot 应用程序中,我有一个支持 bean,我在其中使用 JSR303 验证。在注释中,我已经指定了消息代码:

@NotBlank(message = "{firstname.isnull}")
private String firstname;

然后在我的 message.properties 中指定:

firstname.isnull = Firstname cannot be empty or blank

messageSource 的 JavaConfig 是:

@Bean(name = "messageSource")
public MessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("messages");
    messageSource.setDefaultEncoding("UTF-8");
    return messageSource;
}

验证工作正常,但我没有看到实际的字符串,而是在我的 jsp 页面中获得了消息代码。在查看日志文件时,我看到了一系列代码:

Field error in object 'newAccount' on field 'firstname': rejected value []; codes [NotBlank.newAccount.firstname,NotBlank.firstname,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [newAccount.firstname,firstname]; arguments []; default message [firstname]]; default message [{firstname.isnull}]

如果我将 message.properties 中的消息代码更改为数组中的代码之一,该字符串将正确显示在我的 Web 表单中。我什至不必更改注释中的代码。这向我表明注释的消息参数中的代码被忽略了。

我不想使用默认代码。我想用我自己的。我怎样才能使这项工作。能否提供一个代码示例。

【问题讨论】:

    标签: spring-boot bean-validation


    【解决方案1】:

    JSR303 插值通常适用于 ValidationMessages.properties 文件。但是,您可以根据需要配置 Spring 来更改它(我很懒惰这样做:))例如

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="validationMessageSource" ref="messageSource" />
    </bean>
    
    <mvc:annotation-driven validator="validator" />
    

    【讨论】:

    • 太棒了!我只需要将文件名更改为 ValidationMessages.properties 就可以了!我什至不需要@Bean 配置(因为我使用的是 SpringBoot)。我会投票给你的答案,但显然我需要更好的声誉。谢谢!
    • 很高兴为您提供帮助。如果解决方案有效,您至少可以接受它(我相信)
    • 已接受。看起来像一些善良的灵魂投票。再次感谢。
    【解决方案2】:

    根据JSR-303 specification消息参数预计存储在ValidationMessages.properties文件中。但是您可以覆盖寻找它们的位置。

    所以你有两个选择:

    1. 将您的消息移至ValidationMessages.properties 文件
    2. 或覆盖WebMvcConfigurerAdapter 的后代的getValidator() 方法(在您的情况下为JavaConfig):

      @Override
      public Validator getValidator() {
          LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
          validator.setValidationMessageSource(messageSource());
          return validator;
      }
      

    【讨论】:

    • 规范中的措辞声明“经常具体化为属性文件 /ValidationMessages.properties 及其语言环境变体”(强调我的)。规范中没有规定文件名。
    猜你喜欢
    • 2014-10-06
    • 2017-05-04
    • 2012-05-19
    • 1970-01-01
    • 2018-07-07
    • 2021-01-23
    • 1970-01-01
    • 2013-11-05
    • 2016-01-13
    相关资源
    最近更新 更多