Spring 注释中的引导 JSR303 消息代码被忽略

Spring Boot JSR303 message code in annotation getting ignored

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

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

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

firstname.isnull = Firstname cannot be empty or blank

我的消息源 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 表单中正确显示。我什至不必更改注释中的代码。这向我表明注释的消息参数中的代码被忽略了。

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

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

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

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

根据 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;
    }