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

use*_*124 8 bean-validation spring-boot

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

@NotBlank(message = "{firstname.isnull}")
private String firstname;
Run Code Online (Sandbox Code Playgroud)

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

firstname.isnull = Firstname cannot be empty or blank
Run Code Online (Sandbox Code Playgroud)

我对MessageSource的JavaConfig是:

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

验证工作正常,但我没有看到实际的字符串,而是在我的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}]
Run Code Online (Sandbox Code Playgroud)

如果我将message.properties中的消息代码更改为数组中的某个代码,则该字符串将在我的Web表单中正确显示.我甚至不必更改注释中的代码.这向我指示注释的message参数中的代码被忽略.

我不想使用默认代码.我想用自己的.我怎样才能做到这一点.能否请您提供代码示例.

sod*_*dik 9

JSR303插值通常适用于ValidationMessages.properties文件.但是你可以配置Spring来改变它,如果你想(我很懒,这样:))例如

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

<mvc:annotation-driven validator="validator" />
Run Code Online (Sandbox Code Playgroud)


Lu5*_*u55 5

根据JSR-303规范,消息参数预计存储在ValidationMessages.properties文件中.但是你可以覆盖他们寻找的地方.

所以你有两个选择:

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

    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource());
        return validator;
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 规范中的措辞陈述"**经常**实现为属性文件/ValidationMessages.properties及其区域变体"(强调我的).文件名未在规范中规定. (2认同)