0

I'm trying to change the language of the email template based on the users preferred language (ID of the preferred language is stored in the user table). When preparing the message I pass the Locale to the Context as shown below:

Locale locale = new Locale(user.getLanguage().getLocaleCode());
final Context ctx = new Context(locale);
ctx.setVariable("username", user.getUsername());
ctx.setVariable("address", user.getAddress());

When I log the result of the getLocaleCode() it returns the expected value, for example 'sr'. Inside my /resources/lang folder I have created messages_sr.properties file. But for some reason when I send the email it will always use the language in the default messages.properties. Here is my configuration file:

@Configuration
public class LocaleConfig {

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.US);
        return slr;
    }
    
    @Bean(name = "messageSource")
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:lang/messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
}

Inside the resources/lang folder I have:

  • messages_en_US.properties
  • messages_sr.properties

Based on the documentation and examples I was able to find I couldn't find the solution. Can anyone please help?

Thanks.

D3jan244
  • 23
  • 5
  • You don't need to create the `messageSource` bean if you just want to put the translations in a subfolder. I use `spring.messages.basename=i18n/messages` on all my projects so they can be in `src/main/resources/i18n/` directory. – Wim Deblauwe Sep 17 '20 at 05:25

1 Answers1

0

Inspired by https://stackoverflow.com/a/11152674/3849555, please use classpath*:lang/messages instead.

Chayne P. S.
  • 1,558
  • 12
  • 17