Java library containing Spring MessageSource and message properties files

Viewed 16

I'm developing a shared library containing some UI components for Spring (Boot) applications.

I want the library to contains the translations for the text of its own components. My idea was to create a ResourceBundleMessageSource in the library, along with the message properties files containing the translations.

I create the message source like this:

    this.localMessageSource = new ResourceBundleMessageSource();
    localMessageSource.setDefaultEncoding("UTF-8");
    localMessageSource.setBasename("mymessages"); // I have also tried "classpath:mymessages"

And I have tried putting the mymessages.properties, mymessages_nl.properties etc. files in /src/main/resources and in /src/main/resources/META-INF, but when calling the code that accesses this MessageSource to get the messages, they are not found. In the debugger, I can see that the resource bundle is not found at all.

What do I need to change to make this work?

1 Answers

I was able to solve this using the following method:

  • The service that uses the library has its own MessageSource bean which is a ResourceBundleMessageSource
  • The library code has a resource bundle e.g. mymessages in /src/main/resources
  • At an appropriate place in a bean that is configured in the library code, add the basename for this resource bundle to the injected MessageSource like this:
((ResourceBundleMessageSource)messageSource).addBasenames("mymessages");

In my case, in the library I have a singleton bean which implements com.vaadin.flow.i18n.I18NProvider and delegates the getTranslation() method to the messageSource.getMessage() method, so the constructor of this bean is an appropriate place to add the base name for the additional resource bundle to the already configured MessageSource.

Related