javaspringinternationalizationpluralizeicu4j

Pluralization issues within spring boot project


Currently I'm using Spring-boot + Thymeleaf and multiple languages. I can't find any easy way to use ICU4j with these. Essentially, as I get it, all what is need is to replace ResourceBundleMessageSource and its MessageFormat with the ICU4J variant. But I can't make it work together.

Maybe there is some examples of such projects or any other examples of pluralization functionality in Spring (such as this).


Solution

  • With the typical Spring Boot 2 + Thymeleaf project it can be achieved with this project and the following config:

    @Configuration
    public class YourConfigFile ...
    
    @Bean
    public ICUMessageSource messageSource() {
        ICUReloadableResourceBundleMessageSource messageSource = new ICUReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages/messages");
        messageSource.setCacheSeconds(3600);
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
    

    You also need to add the ICU4J dependency from the maven.

    In your messages.properties (messages_ru.properties in my case):

    plural={0} {0, plural, one{пользователь}few{пользователя}other{пользователей}}
    

    Using:

    <span th:text="#{plural(0)}"></span>
    <span th:text="#{plural(1)}"></span>
    <span th:text="#{plural(2)}"></span>
    <span th:text="#{plural(10)}"></span>
    

    If you have troubles with finding messages.properties end getting errors like ??plural_ru??, check your location and names for these files messageSource.setBasename("classpath:messages/messages").