Internationalization of Spring Boot RESTful Services
If your application serves a wide range of clients spanning across the globe, it becomes essential to be able to respond based on country and language of the origin of request. Internationalization is the processes of designing your application to be capable of the same. During the course of this article we will create a simple Spring Boot App with a single endpoint that can serve the same text in various languages.
Code Structure
spring-boot-i18n
│ .gitignore
│ HELP.md
│ mvnw
│ mvnw.cmd
│ pom.xml
│
└───src
├───main
│ ├───java
│ │ └───com
│ │ └───techgoons
│ │ └───i18n
│ │ I18nController.java
│ │ SpringBootI18nApplication.java
│ │
│ └───resources
│ application.properties
│ messages.properties
│ messages_de.properties
│ messages_es.properties
│ messages_fr.properties
│ messages_nl.properties
│
└───test
└───java
└───com
└───techgoons
└───i18n
SpringBootI18nApplicationTests.java
You can use the spring boot initializer to generate the template with spring-boot-starter-web dependency.
How to enable i18n messaging in a spring boot app?
Update the application.properties as below. Explanation for each configuration has been added as comments
Resource Bundles
As specified in the application.properties, application will look for messages*.properties named files for fetching content.
messages.properties — the default file will contain English key value pairs
welcome=Welcome to Tech Goons homepage
messages_de.properties — German
welcome=Willkommen auf der Tech Goons-Homepage
messages_es.properties — Spanish
welcome=Bienvenido a la página de inicio de Tech Goons
messages_fr.properties — French
welcome=Bienvenue sur la page d'accueil de Tech Goons
messages_nl.properties — Dutch
welcome=Welkom op de startpagina van Tech Goons
All translations have been generated using Google translate. Apologies in advance if certain translations are not correct.
Rest Controller
We will keep the controller simple and expose just a single endpoint that will fetch the welcome message from resource bundle based on Accept-Language header in the request.
We autowire the MessageSource component which has the necessary means to fetch values from appropriate resource bundle based on language details passed in request header.
Testing!
After starting the server you can try out below cURL commands.
curl --location --request GET 'localhost:8080/' --header 'Accept-Language: de'OUTPUT: Willkommen auf der Tech Goons-Homepagecurl --location --request GET 'localhost:8080/' --header 'Accept-Language: es'OUTPUT: Bienvenido a la p�gina de inicio de Tech Goons
Source code here. Happy Learning!