Why do I need Spring Boot `messages.properties` instead of just `messages_en.properties`?

2.3k views Asked by At

I'm following this guide and it says to name the default messages file as messages.properties. Why can't I name it messages_en.properties and set the default locale to English?

@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver slr = new SessionLocaleResolver();
    slr.setDefaultLocale(Locale.ENGLISH);
    return slr;
}

This doesn't work (have to hard stop and restart the server each time message.properties is renamed - dynamic reload fails to pick up the changes). It will print out default text with a tag like <spring:message code="oops" text="default"/> because it can't find messages_en.properties.

In fact, when I set my browser default language to French and have messages_fr.properties, and restart the server, it is also failing to find the keys for French as well.

Not using Thymeleaf. No need to allow user-selectable language.

Reference: https://docs.spring.io/spring-boot/docs/1.5.17.RELEASE/reference/htmlsingle/ (Only one instance of the world 'internationalization', and only regarding application properties).

1

There are 1 answers

5
Chloe On BEST ANSWER

I fixed it by using AcceptHeaderLocaleResolver instead.

@Bean
public LocaleResolver localeResolver() {
    AcceptHeaderLocaleResolver ahlr = new AcceptHeaderLocaleResolver();
    ahlr.setDefaultLocale(Locale.ENGLISH);
    return ahlr;
}

I thought the guide said it will search for the locale in the session, cookie, or header, but they were only saying that different sub-classes implement those features separately.

The LocaleResolver interface has implementations that determine the current locale based on the session, cookies, the Accept-Language header, or a fixed value.

I fixed the live reload problem by setting this application property, at least for debugging:

spring.messages.cache-seconds=1

I also set this property so as not to clutter up my src/main/resources folder, so I could move all the message files into the locales/ sub-directory.

spring.messages.basename=locales/messages