본문 바로가기
코딩 공부/web & Java

[Spring] 국제화

by 현장 2023. 11. 12.

국제화

다른 언어를 사용하는 전 세계의 사용자들에게 REST API를 사용자 정의할때 필요입니다. 이때 홈페이지의 내용을 다국어로 지원해주는 것, 국제화를 사용합니다.

 

이때, i18n을 Accept-Language라는 것을 사용하여 국제화를 적용합니다.

i18n(18개의 언어 Internationalization)
Accept-Language를 통하여 i18n 을 사용하 Accept-Language는 사용자가 선호하는 언어와 지역을 나타냅니다.

 

🏷️ 예시코드

다음과 같이 메세지를 반환을 하게 하려면 message.properties가 필요하게 됩니다.

// 국제화 예시
@GetMapping(path = "/hello-world-internationalized")
public String helloworldInternationalized() {
    /*
    retern 값
    en = Good Morning
    ko = 좋은 아침입니다
    fr = Bonjour
    nl = Goedemorgen
    */
}

 

 

다음과 같이 리소스 파일 안에 messages.properties 를 생성합니다. 단, 파일명이 틀리게 되면 인식을 못하니 주의해야 합니다.

// messages.properties 파일
good.morning.message=Good Morning

// messages_nl.properties 파일
good.morning.message=Goedemorgen

 

그리고 프로퍼티에 작성된 메세지를 사용하고 싶다면

private MessageSource messageSource;

public HelloWorldController(MessageSource messageSource) {
    this.messageSource = messageSource;
}

 

라는 것이 필요합니다.

MessageSource란
MessageSource는 국제화(i18n) 기능을 제공하는 인터페이스입니다. 메시지를 다국화하는 방법을 정의하며 메시지 파일을 모아놓고 각 국가마다 지역화함으로써 각 지역에 맞춘 메시지를 제공할 수 있습니다.

 

이 MessageSource에서 메시지를 받아오고자 할 때 getMessage 를 통하여 아래와 같이 메시지를 받아올 수 있습니다.

// 국제화 예시
@GetMapping(path = "/hello-world-internationalized")
public String helloworldInternationalized() {
 	// 현제 스레드와 관련된 지역 또는 언어를 나타내는 정보를 포함하는 객체(로케일)을 가져옴
    // 없다면 default locale을 가져옵니다. 
    Locale locale = LocaleContextHolder.getLocale();
   
    return messageSource.getMessage("good.morning.message", null, "Default Message", locale);
}

/* 
    이때 입력 변수로는 아래와 같습니다.
    Code : 메세지 변수명
    Args : any variables to replace
    Default Message : 기본 메시지
    Locale : 사용자 로케일 정보
*/

 

결과는 아래와 같습니다.

'코딩 공부 > web & Java' 카테고리의 다른 글

[Spring] HATEOAS  (1) 2023.11.14
[Spring] REST API 버전 관리  (0) 2023.11.12
OpenAPI와 Swagger  (1) 2023.11.09
[Docker] Docker  (0) 2023.11.08
[Spring] RequestParam과 PathVariable  (0) 2023.11.07