This is a quick blog post on how to add locale support for your REST API's using spring-boot. In this example you will learn to send localized content based on the Accept-Language header.
Accept-Language: Language Tag
eg:
* Send an API request with Accept-Language: en , you will get English language content.
* end an API request with Accept-Language: zh , you will get Chinese language (mandarin) content.
You can check the supported language tags from here.
https://www.oracle.com/java/technologies/javase/jdk8-jre8-suported-locales.html
Assume that your back-end needs to send localized contents based on the language choose from the front end application.
The easiest way is to keep this localized messages in a Resource bundle for each language. You can do this by using the ResourceBundleMessageSource.
Create a new resource bundle in src/main/resources directory. This directory holds the property files for each language. I have created a resource bundle named as menu and it contains 2 property files for both English and Chines (Mandarin) languages. A property file contain a key and value pairs. Key will be the message code and value is the actual message. You can add any no of language files as per your requirement. Let's take a look at the property files.
menu.propertiesNow we need to create a bean class to set these files to a ResourceBundleMessageSource.
package com.rkdevblog.configuration; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.context.support.ResourceBundleMessageSource; | |
@Configuration | |
public class ResourceBundleMessageSourceBean { | |
/** | |
* Set the list of resource files here | |
* | |
* @return resourceBundleMessageSource | |
*/ | |
@Bean | |
public ResourceBundleMessageSource messageSource() { | |
ResourceBundleMessageSource rs = new ResourceBundleMessageSource(); | |
rs.setBasenames("menu"); | |
rs.setDefaultEncoding("UTF-8"); | |
rs.setUseCodeAsDefaultMessage(true); | |
return rs; | |
} | |
} |
package com.rkdevblog.configuration; | |
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 final ResourceBundleMessageSource messageSource; | |
@Autowired | |
Translator(ResourceBundleMessageSource messageSource) { | |
this.messageSource = messageSource; | |
} | |
public String toLocale(String msgCode) { | |
Locale locale = LocaleContextHolder.getLocale(); | |
return messageSource.getMessage(msgCode, null, locale); | |
} | |
} |
Comments
Post a Comment