Spring Boot || Tutorial 11 || Handling Internationalization (i18n) using Spring boot - NESTED CODE || TECH FLOAT

Breaking

Post Top Ad

Post Top Ad

Sunday, 29 March 2020

Spring Boot || Tutorial 11 || Handling Internationalization (i18n) using Spring boot


Hope you all have already explored our basic courses on Spring Boot.
Now onward we will be sharing blog tutorials on some advanced versions of the same.

Today we will discuss on how to set up or enable internationalization (i18n) facility for spring boot.

What is internationalization?

It is a feature or functionality that enables or provide us an option to read or show the content in different languages. For example if a person belongs to USA region would like to read webpage data or any other data in US English – where a person belongs to Spain would like to read the same in spanish.

Spring provides this internationalization feature to achieve the above mentioned requirement. Lets understand with below example.

Please follow the below mentioned steps to enable internationalization:

Step-1: At very first, we need to enable a bean of LocaleResolver. Please use the below mentioned code in your Application stater class or any other class which is mentioned for Bean handling.

We would prefer to declare this in Application stater (the main method class)
@Bean
public LocaleResolver localeResolver(){
AcceptHeaderLocaleResolver localeResolverObj = new AcceptHeaderLocaleResolver();
localeResolverObj.setDefaultLocale(Locale.US);
return localeResolverObj;
}


Step-2: Create properties file which will have different message for US English and Spanish.

Let's give below name :

(a) messages.properties → Default file contains US English message
message.default="Hello Nc Team!"
(b) messages_sp.properties → same message in Spanish
message.default="Hola Nc Team!"
Make sure the above files are in src/main/resources folder.

Now go to application.properties file and enable the below line:
spring.messages.basename=messages

Step-3: Now all you need to do is write end point in controller class. Use below code as sample.

@Autowired
private MessageSource message;
@GetMapping("/message")
public String getMessage(){
return message.getMessage("message.default"null, LocaleContextHolder.getLocale());
}

That's all, now execute the project and trigger the end point as shown in below image.



No comments:

Post a Comment

Post Bottom Ad