
만약 여러분의 제품을 전세계 사람들이 사용한다고 했을 때 서로 다른 언어를 사용하는 사용자들에게 맞는 언어를 제공하기 위해서 어떻게 할까요?
이때, Internationalization(i18n) = 국제화를 사용해야 합니다.
국제화를 처리할 때마다 Accept-Language라는 HTTP Request Header를 사용합니다.
자연어와 소비자가 선호하는 로케일을 나타냅니다.
Accept-Language: en-US,en;q=0.9,ko;q=0.8
HelloWorldController를 통해 사용해보겠습니다.
package study.rest.webservices.restfulwebservices.helloworld;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@GetMapping("/hello-world")
public String helloWorld() {
return "Hello World";
}
@GetMapping("/hello-world-bean")
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean("Hello World");
}
@GetMapping("/hello-world/path-variable/{name}")
public HelloWorldBean helloWorldBeanPathVariable(@PathVariable String name){
return new HelloWorldBean(String.format("Hello World, %s", name));
}
@GetMapping("/hello-world-internationalized")
public String helloWorldInternationalized() {
return "Hello World V2";
}
}
본격적으로 국제화 기능을 구현해보겠습니다.
먼저 해당 국가의 언어를 저장하고 있는 파일이 있어야합니다.
good.morning.message=Good Morning
메세지를 저장했으니 사용할 수 있어야겠죠?
package study.rest.webservices.restfulwebservices.helloworld;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Locale;
@RestController
public class HelloWorldController {
private MessageSource messageSource;
public HelloWorldController(MessageSource messageSource) {
this.messageSource = messageSource;
}
@GetMapping("/hello-world")
public String helloWorld() {
return "Hello World";
}
@GetMapping("/hello-world-bean")
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean("Hello World");
}
@GetMapping("/hello-world/path-variable/{name}")
public HelloWorldBean helloWorldBeanPathVariable(@PathVariable String name){
return new HelloWorldBean(String.format("Hello World, %s", name));
}
@GetMapping("/hello-world-internationalized")
public String helloWorldInternationalized() {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage("good.morning.message", null, "Default Message", locale);
}
}
LocaleContextHolder.getLocale(): 현재 스레드에 바인딩된 Locale 정보를 가져오는 메서드입니다.
messageSource.getMessage(): “good.morning.message”라는 키의 메세지를 출력합니다. 메세지가 없다면 기본메세지를 출력합니다.
Good Morning이라는 글씨가 잘 나오는 걸 볼 수 있습니다.

이번에는 한글이 나오게 해보겠습니다.
