Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot JSR303 message code in annotation getting ignored

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.

like image 873
user3137124 Avatar asked Feb 13 '15 04:02

user3137124


2 Answers

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" />
like image 163
sodik Avatar answered Oct 13 '22 20:10

sodik


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;
    }
    
like image 24
Lu55 Avatar answered Oct 13 '22 22:10

Lu55