Alex
Alex

Reputation: 2030

Spring MessageSource find by several locales

I have following case: I'm getting a list of locales from mobile and I need to check my MessageSource whether it has any matches with the passed list. So by default, I can check by one locale and if spring doesn't find a match it will use default locale but in my case, I need to check the list of locales. Is there any support for this feature in spring?

Upvotes: 0

Views: 1573

Answers (1)

Alex
Alex

Reputation: 2030

I was able to fix it in following way:

    @Bean
    public CustomMessageSource messageSource() {
        CustomReloadableResourceBundleMessageSource messageSource = new CustomReloadableResourceBundleMessageSource();
        messageSource.setFallbackToSystemLocale(false);
        messageSource.setBasename("messages");
        return messageSource;
    }


    public class CustomReloadableResourceBundleMessageSource extends
    ResourceBundleMessageSource implements CustomMessageSource {
    public String getMessage(String code, List<Locale> locales) {
        return locales.stream().map(locale -> getMessage(code, null, locale))
            .filter(StringUtils::isNotEmpty).findFirst()
            .orElse(getMessage(code, null, Locale.ENGLISH));
    }
}

Setting fallbackToSystemLocale property to false was pretty important because otherwise system used default locale for each unresolved message.

Upvotes: 1

Related Questions