Learn how to transform your Spring Boot application into a multilingual powerhouse, enabling it to seamlessly adapt to various languages and regions without the need for source code modifications. Dive into the world of Spring Boot’s Internationalization (i18n) capabilities, simplifying your journey to serve a global audience.
This comprehensive blog guides you through the key phases, starting from project creation via Spring Initializr, and moving on to custom locale management and message translation. By the end, you’ll be well-versed in crafting a user-friendly, multilingual application, ushering in a new era of diverse user experiences.
Internationalization (i18n) is the process of making your application adaptable to different languages and regions without engineering changes to the source code. This means that users from different countries can see your application in their preferred language, with the correct date and time formats, currencies, and other locale-specific information.
Spring Boot provides excellent support for internationalization (i18n), simplifying the process of making your REST APIs multilingual. To achieve this, you can utilize Spring Initializr, which streamlines project creation by offering a guided selection of the required dependencies.
Related read: Localization with react native i18n: A Comprehensive Guide
Then click Generate Project, unzip it and open it with your favourite IDE. I’ll use Eclipse IDE.
The first step is to create a CustomLocaleResolver class to define the user’s locale.
package com.mb.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver; import jakarta.servlet.http.HttpServletRequest; import java.util.Arrays; import java.util.List; import java.util.Locale; @Configuration public class CustomLocaleResolver extends AcceptHeaderLocaleResolver implements WebMvcConfigurer { List<Locale> LOCALES = Arrays.asList( new Locale("en"), new Locale("fr")); @Override public Locale resolveLocale(HttpServletRequest httpRequest) { String langHeader = httpRequest.getHeader("Accept-Language"); return langHeader == null || langHeader.isEmpty() ? Locale.getDefault() : Locale.lookup(Locale.LanguageRange.parse(langHeader), LOCALES); } @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource rs = new ResourceBundleMessageSource(); rs.setBasename("messages"); rs.setDefaultEncoding("UTF-8"); rs.setUseCodeAsDefaultMessage(true); return rs; } }
This project supports three locales: English, Hindi, and French. The locale should be passed in the Accept-Language header. If the header is present and not empty, we will use the locale from the header. Otherwise, we will use the default locale, which is English.
Next, let’s create our class that will be responsible for choosing the right message according to the specified locale. I’ll call it Translator, and it will have one single method, that will accept the message code that should be translated.
package com.mb.util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.stereotype.Component; import java.util.Locale; @Component public class Translator { private static ResourceBundleMessageSource messageSource; @Autowired Translator(ResourceBundleMessageSource messageSource) { Translator.messageSource = messageSource; } public static String toLocale(String msg) { Locale locale = LocaleContextHolder.getLocale(); msg = msg.replaceAll(" ", "_"); msg = msg.toLowerCase(); return messageSource.getMessage(msg, null, locale); } }
The messageSource.getMessage() method accepts a message code as a parameter, not the message itself. We need to create message codes for our messages before we can translate them.
Create three files in the resources folder: messages.properties,messages_hi.properties and messages_fr.properties.
➡️ The following is the content of messages.properties:
hello = hello bye = bye thank_you = thank you congratulations = congratulations !!!! how_are_you = How are you ???
➡️ The following is the content of messages_fr.properties:
hello=Bonjour bye=Au revoir thank_you = merci congratulations = toutes nos félicitations how_are_you = comment vas-tu ?
➡️ The following is the content of messages_hi.properties:
hello = \u0928\u092E\u0938\u094D\u0924\u0947 bye = \u0905\u0932\u0935\u093F\u0926\u093E thank_you = \u0927\u0928\u094D\u092F\u0935\u093E\u0926 congratulations = \u092C\u0927\u093E\u0908 \u0939\u094B how_are_you = \u0906\u092A \u0915\u0948\u0938\u0947 \u0939\u0948\u0902
We now have message codes, such as hello and bye etc. To get the appropriate message according to the user’s locale, we pass the message code to the toLocale() method.
The last step is to create a simple controller, which we can call MainController. It will have a single endpoint that accepts a message code as a request parameter.
package com.mb.controllers; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.mb.util.Translator; @RestController @RequestMapping("/api") public class MainController { @GetMapping("/msg") public String getMessage(@RequestParam("msg") String message) { return Translator.toLocale(message); } }
To run the InternationalizationInSpringBoot application, you can right-click on the project in your IDE and select “Run as > Spring Boot Application”.
And make simple requests using Postman:
As you can see, the responses differ depending on the value of the Accept-Language header passed in the request. This way, we can avoid checking the request for this value in each controller method and passing it to service layers. Instead, we can do it in a single place, in the CustomLocaleResolver class.
In conclusion, this blog has taken you on a journey into the realm of internationalization within Spring Boot applications. By embracing internationalization (i18n), you can make your application adaptable to various languages and regions without needing extensive changes to your source code. We explored the robust support for i18n provided by Spring Boot, allowing effortless multilingualization of your REST APIs.
From creating a project using Spring Initializr to implementing custom locale handling and message translation, we’ve equipped you with the knowledge to develop user-friendly, multilingual applications, catering to a diverse global audience.
The full source code for the example is available on GitHub.
The team at Mindbowser was highly professional, patient, and collaborative throughout our engagement. They struck the right balance between offering guidance and taking direction, which made the development process smooth. Although our project wasn’t related to healthcare, we clearly benefited...
Founder, Texas Ranch Security
Mindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork