HandsomeBeardMan
HandsomeBeardMan

Reputation: 23

How to fix 'parentMessageSource of the messageSourceBean' so it's not always null

I am creating an API with spring boot with custom validation messages and I am always getting the org.springframework.context.NoSuchMessageException: No message found under code 'name.of.my.message' for locale 'en_US' exception when I try to get the messages from the messages.properties file.

At first I thought it was because of the locale so I tried to have my own LocaleResolver @Bean to set the default locale to US and change the messages.properties file name to messages_en_us.properties, but it did not fix the issue.

I finally thought that maybe it was because of the messageSource object and I think I was right. When I debugged, I saw that the messageSource object has parentMessageSource at null and when I stepped into the getMessage() method, I saw that if parentMessageSource is null it will throw the NoSuchMessageException. I am not finding a lot about this specific issue, this is why I am asking this question here.

This my code in application.java (until I make it work):

@Bean
public MessageSource messageSource() {

    ResourceBundleMessageSource messageSource = new 
        ResourceBundleMessageSource ();

    messageSource.setBasename("classpath:messages");
    messageSource.setDefaultEncoding("UTF-8");
    return messageSource;
}   

@Bean
public LocalValidatorFactoryBean validator(MessageSource messageSource) {
    LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
    bean.setValidationMessageSource(messageSource());
    return bean;
}

messages.properties :

user.firstName.NotNull=First name must not be null.

From all the tutorials I read, this is only what I need to get my validation messages, but, because of the parentMessageSource at null, it is not possible even if the rest of my code seems okay.

Upvotes: 1

Views: 1044

Answers (1)

HandsomeBeardMan
HandsomeBeardMan

Reputation: 23

Well I found the solution.

It was quite simple actually. My own misunderstanding of Spring boot is at fault here. Basically, in my test class, I need to add the annotations @ConfigurationContext (classes = Application.java, MyCustomValidationConfig.java)and it worked ! Thanks to everyone who took a look. Now I just need to figure out out test @valid !

Upvotes: 0

Related Questions