This forum is now a read-only archive. All commenting, posting, registration services have been turned off. Those needing community support and/or wanting to ask questions should refer to the Tag/Forum map, and to http://spring.io/questions for a curated list of stackoverflow tags that Pivotal engineers, and the community, monitor.

Getting localized strings from code

Jun 25th, 2012, 08:28 AM

Hi everybody,
I need to reproduce the behaviour of spring:message tag in java classes.

The scenario is:
- User registers himself
- I have to send an automatic email to a user upon registration
- the user has chosen a preferred language
- I must send a localized mail
- different mail bodies are stored in the localization files (messages.properties, for exampe)
- I need to get the localized mail body from the resources

I've tried to start from LocalContextHolder, but I didn't find any method to read a localized string.

Spring has MessageSource interface that can be used to get localized strings with the getMessage() methods. ResourceBundleMessageSource can be used to read message from standard Java messages.properties files.

When using Spring MVC, you should automatically get an implementation of this interface in your app context. Assuming you are using a current version of Spring, you can just @Autowired a MessageSource into your code.