Spring Boot JSR303 message code in annotation getting ignored

自作多情 提交于 2019-11-28 00:19:15

问题


In my Spring Boot app I have a backing bean where I am using JSR303 validation. In the annotation, I have specified the message code:

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

Then in my message.properties I have specified:

firstname.isnull = Firstname cannot be empty or blank

My JavaConfig for the messageSource is:

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

The validation works correctly but instead of seeing the actual string, I get the message code in my jsp page. In looking at the log file, I see an array of codes:

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

If I change the my message code in the message.properties to one of the codes in the array, the string displays correctly in my web form. I didn't even have to change the code in the annotation. This indicates to me the code in the message parameter of the annotation is getting ignored.

I don't want to use the default code. I want to use my own. How can I make this work. Can you please provide a code example.


回答1:


JSR303 interpolation normally works with ValidationMessages.properties file. However you can configure Spring to change that if you want (I was lazy to do so :)) e.g.

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

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



回答2:


According to JSR-303 specification message parameters are expected to be stored in ValidationMessages.properties files. But you can override the place where they are looked for.

So you have 2 options:

  1. Move your messages to the ValidationMessages.properties file
  2. Or override getValidator() method of your WebMvcConfigurerAdapter's descendant (JavaConfig in your case):

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


来源:https://stackoverflow.com/questions/28492763/spring-boot-jsr303-message-code-in-annotation-getting-ignored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!