Spring boot - cannot set default Locale

Patryk kowalski picture Patryk kowalski · Jan 4, 2018 · Viewed 14.9k times · Source

I am now developing Spring Boot application (only rest controllers). Each request to my server contains language tag. I would like to send response in specific language according to this tag. Controllers extract those tags from request and provide to service layer as a Locale instance. I have created properties file under src/main/resources, like this: https://i.stack.imgur.com/fsXPG.jpg.

My problem is with default language. Regardless of provided Locale, messages returned from properties file are always from AppResources_pl.properties. I think that, problem is with default locale. For now i tryied two different ways and still don't know how to set default properties file to english.

First:

ResourceBundle myResources = ResourceBundle.getBundle("AppResources", currentLocale);
String message = myResources.getString("label.error");

Second:

@Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.forLanguageTag("en-US"));
        return slr;
    }

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

and in service:

messageSource.getMessage("label.error", null, locale)

Both way returning message but always from AppResources_pl.properties. How can i set AppResources.properties as a default properties file when provided locale is not found under *.properties files?

Answer

reconnect picture reconnect · Mar 14, 2018

I found that in MessageSourceAccessor default locale is null, so used system locale. This issue appeared in the last versions because about 6 months ago I used provided in original comment configuration with LocaleResolver and it's worked fine.

Solved issue in following line return new MessageSourceAccessor(messageSource, Locale.US); (directly passed Locale)

@Bean(name = "messageSource")
public ReloadableResourceBundleMessageSource getMessageSource() {
    final ReloadableResourceBundleMessageSource res = new ReloadableResourceBundleMessageSource();
    res.setDefaultEncoding("UTF-8");
    res.setFallbackToSystemLocale(false); // will force to use specified locale even if locale for current env is different
    res.addBasenames("classpath:messages/validation", "classpath:messages/messages", "classpath:messages/titles");
    return res;
}


@Bean
public MessageSourceAccessor getMessageSourceAccessor(final MessageSource messageSource) {
    return new MessageSourceAccessor(messageSource, Locale.US);
}