Internationalization in Spring Boot

In the previous tutorial, I showed you how to implement internationalization in Spring MVC applications. For Spring Boot applications, how to implement internationalization? I will guide you in this tutorial!

First, I will create a new Spring Boot project:

Internationalization in Spring Boot

with Spring Web dependency:

Internationalization in Spring Boot

as an example.

Result:

Internationalization in Spring Boot

I will configure it to use InternalResourceViewResolver in this example.

I will declare tomcat-embed-jasper dependency to render JSP files:

and JSTL dependency to work with JSP page:

Next, I will create a new HelloControler:

to display the home.jsp view file located in the src/main/webapp/WEB-INF/views directory with the following content:

Here, I have declared to use <spring:message /> to work with internationalization in Spring framework. Please see the tutorial Internationalization in Spring MVC to understand more about it!

By default, Spring Boot will use the Tomcat server to run, so you should note that to display the correct language, we need to declare the contentType with a charset encoding UTF-8:

Looks like other runtime servers don’t need it!

And I also need to declare in the application.properties file as follows:

Now, we will declare the necessary Spring beans for internationalization: messageSource, localeResolver and localeChangeInterceptor.

To configure the messageSource, I will create 2 new files messages.properties and messages_vi.properties in the src/main/resources/i18n directory with the contents of each file as follows:

messages.properties:

messages_vi.properties

Spring Boot supports auto configuration for messageSource with ResourceBundleMessageSource implementation. You can declare some of the following properties:

Internationalization in Spring Boot

to use Spring Boot’s default configuration.

For example, I can declare a property:

to declare a messageSource for my example application.

Here, I will not use the default configuration and will declare the bean to use the ReloadableResourceBundleMessageSource class as follows:

For localResolver I will also use CookieLocalResolver:

The localeChangeInterceptor will be configured as follows:

Here, I am using WebMvcConfigurer to add LocaleChangeInterceptor to my application.

Run the app and click between languages to see the results!

Mine is as follows:

Internationalization in Spring Boot

and

Internationalization in Spring Boot

Add Comment