Reputation: 905
Currently I'm implementing a service for sending notifications (SMS, for example) to customers. Service is written in Java, based on Spring Boot.
I'd like to send a message in the recipient's language.
So basically I'd like to have a method, taking some id of the message with the desired localization ("en", "fr", "es") and giving back the correct String. Also configuring some default language (like "en") would be great - to fall back to it if the desired language is not supported.
Any suggestions how to achieve this with Spring Boot?
P.S.: Sorry, yes, I've tried "googling". I've found several internationalization examples, but most of them seem not useful, as they're intended for the whole user interface, not a specific message.
Upvotes: 3
Views: 2552
Reputation: 905
As of now I've resolved the issue initializing MessageSource manually:
@PostConstruct
public void initMessageSource() {
ReloadableResourceBundleMessageSource reloadableMessageSource = new ReloadableResourceBundleMessageSource();
reloadableMessageSource.setDefaultEncoding("UTF-8");
reloadableMessageSource.setBasename(config.getI18nBundleBase());
reloadableMessageSource.setCacheSeconds(config.getI18nCacheSeconds());
this.messageSource = reloadableMessageSource;
}
Autowiring initialized my messageSource with empty DelegatingMessageSource, so internationalization did not work.
Upvotes: 0
Reputation: 44939
First, you need to create a couple resource files. Put a file called messages_en.properties
and another called messages_fr.properties
in src/main/resources
.
In the en file put a line:
hello.world=Hello World!
In the fr file put a line:
hello.world=Bonjour le monde!
Then where ever you need to get this text inject a MessageSource
@Autowired private MessageSource messageSource;
Then you can use it to get the text
messageSource.getMessage("hello.world", null, locale);
You'll need to pass in the locale of the user to that method. You can setup a LocaleResolver to do that if you need.
Upvotes: 6