본문 바로가기
백엔드/Spring(Boot)

스프링 메시지, 국제화

by 김어찐 2021. 9. 23.
728x90

메시지

하드코딩된 HTML 문자열들을 별도의 파일("messages.properties")에서 변수로 관리하는 방법

 

국제화

메시지에서 설정한 파일("messages.properties")을 각 나라별로 별도로 관리하면 서비스를 국제화 할 수 있다.

"messages_en.properties" 설정 파일

item=Item

item_id = Item Name



"messages_ko.properties" 설정 파일

item=상품

item_id = 상품 ID

 

접근 인식 방법은 HTTP "accept-language" 헤더 값을 사용하거나 사용자가 직접 언어를 선택하도록 하고, 쿠키 등을 사용해서 처리하면 된다.

 

스프링부트인 경우 application.properties에서 설정해 주면된다.

 

message 테스트 코드

package hello.itemservice.message;


import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;

import java.util.Locale;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

@SpringBootTest
public class MessageSourceTest {

    @Autowired
    MessageSource messageSource;

    @Test
    void helloMessage(){
        // locale 정보가 없으므로 default 값인 message.properties에서 조회
        String result = messageSource.getMessage("hello", null, null);
        assertThat(result).isEqualTo("안녕");
    }

    @Test
    public void notFoundMessageCode() throws Exception{
        //given
        //message.properties 에서 no_code 가 있는지 확인(파일에는 없음)
        assertThatThrownBy(() ->messageSource.getMessage("no_code",null,null)).isInstanceOf(NoSuchMessageException.class);

    }

    @Test
    public void notFoundMessageCodeDefaultMessage() throws Exception{
        // 메세지를 못찾으면 defaultMessage인 "기본 메시지"를 리턴
        String result = messageSource.getMessage("no_code", null,"기본 메시지", null);
        assertThat(result).isEqualTo("기본 메시지");

    }

    @Test
    public void argumentMessage() throws Exception{
        // argument를 줄때는 배열로 넘겨줘야한다
        String message = messageSource.getMessage("hello.name", new Object[]{"Spring"}, null);
        assertThat(message).isEqualTo("안녕 Spring");

    }

    @Test
    void defaultLang(){
        assertThat(messageSource.getMessage("hello", null, null)).isEqualTo("안녕");
        // 해당 locale이 없으면 default 값으로 적용(messages.properties.
        assertThat(messageSource.getMessage("hello", null, Locale.KOREA)).isEqualTo("안녕");
    }

    @Test
    void enLang(){
        assertThat(messageSource.getMessage("hello", null, Locale.ENGLISH)).isEqualTo("hello");
    }
}

 

메세지 적용

타임리프에서 접근할 시 $ 가 아닌 #으로 properties 파일에 접근한다.

#파라미터 적용법

hello.name=안녕 {0}

<p th:text="#{hello.name(매개변수)}"></p>

국제화 적용

지원할 언어(영어)를 message_(en) 붙여준다 현재 default 값이 messages라 아래 그림처럼 파일이름 생성

기본적으로 "accept-language" 헤더 값을 사용해서 국제화 적용

 

쿠키나 세션 기반의 Locale 선택기능을 사용할 수 있다.

LocaleResolver를 상용하면 된다.

728x90