Search code examples
spring-bootspring-data-jpalocalizationinternationalization

Spring boot localization from database


I would like to implement localization on my spring boot application. Localization based on message bundle is working fine. But I need to implement the same from reading locale message from database based on my master table data. What is the best practice to implement this. I want to implement this solution with minimal changes on my existing entity class.


Solution

  • The MessageSource is not, in my opinion, useful for fetching a list of employees by locale.

    It is important to understand that the MessageSource is an API (MessageSourceInterface) that can select a text (for example a translation) using code and locale. Whether you use the code and/or locale in your MessageSource implementation to select a string is up to you. If you look at the MessageSource interface, you will see that getMessage() returns a String, not a list of objects.

    Components for example Validation and Thymeleaf use the MessageSource to select a text. You define the code and optional arguments or/and a DefaultMessage.

    You may also need to implement a fallback in your MessageSource implementation if the locale is not supported.

    The component set the locale.

    [Component] <-> [MessageSource] <-> [DataSource]

    Thymeleaf

    <h1 th:text="#{home_headline}"/>
    

    You can also use the MessageSource directly.

    @Autowired MessageSource messageSource;
    String methodeName() {
        return this.messageSource.getMessage("home_headline", null, null, Locale.forLanguageTag("en"));
    }