본문 바로가기
스프링/스프링 웹 개발 활용

[Spring] 스프링 메시지 소스 사용 및 .properties 파일 인코딩 설정

by drCode 2023. 6. 28.
728x90
반응형

MessageSource 인터페이스

public interface MessageSource {
    String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale);
    String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException;
}

MessageSource 인터페이스를 보면 코드를 포함한 일부 파라미터로 메시지를 읽어오는 기능을 제공한다.

 

스프링이 제공하는 메시지 소스를 어떻게 사용하는지 테스트 코드를 통해서 학습해보자

 

test/java/hello/itemservice/message.MessageSourceTest.java

package hello.itemservice.message;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
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.*;

@SpringBootTest
public class MessageSourceTest {

    @Autowired
    MessageSource ms;

    @Test
    void hellMessage() {
        String result = ms.getMessage("hello", null, null);
        assertThat(result).isEqualTo("안녕");
    }
}

 - ms.getMessage("hello", null, null)

   : code: hello

   : args: null

   : locale: null

 

가장 단순한 테스트는 메시지 코드로 hello 를 입력하고 나머지 값은 null 을 입력했다.

locale 정보가 없으면 basename 에서 설정한 기본 이름 메시지 파일을 조회한다.

basename 으로 messages 를 지정 했으므로 messages.properties 파일에서 데이터 조회한다.

 

만약에 테스트 했는데 "안녕"을 기대했지만, "??" 이 나온다면?

 

Settings 에서 인코딩 설정을 해줘야 한다.

 

프로퍼티 파일 인코딩 설정

기존에 ??이 떴었다면, 다시 테스트를 시도해보자

 

정상적으로 결과가 나올 것이다.

 

MessageSourceTest 추가 - 메시지가 없는 경우, 기본 메시지

@Test
void notFoundMessageCode() {
    assertThatThrownBy(() -> ms.getMessage("no_code", null, null))
            .isInstanceOf(NoSuchMessageException.class);
}

@Test
void notFoundMessageCodeDefaultMessage() {
    String result = ms.getMessage("no_code", null, "기본 메시지", null);
    assertThat(result).isEqualTo("기본 메시지");
}

메시지가 없는 경우에는 NoSuchMessageException 이 발생한다.

메시지가 없어도 기본 메시지( defaultMessage )를 사용하면 기본 메시지가 반환된다

 

MessageSourceTest 추가 - 매개변수 사용

@Test
void argumentMessage() {
    String result = ms.getMessage("hello.name", new Object[]{"Spring"}, null);
    assertThat(result).isEqualTo("안녕 Spring");
}

다음 메시지의 {0} 부분은 매개변수를 전달해서 치환할 수 있다.

hello.name=안녕 {0} Spring 단어를 매개변수로 전달 안녕 Spring

 

국제화 파일 선택

locale 정보를 기반으로 국제화 파일을 선택한다.

 - Locale이 en_US 의 경우 messages_en_US messages_en messages 순서로 찾는다.

 - Locale 에 맞추어 구체적인 것이 있으면 구체적인 것을 찾고, 없으면 디폴트를 찾는다고 이해하면 된다

 

MessageSourceTest 추가 - 국제화 파일 선택1

@Test
void defaultLang() {
    assertThat(ms.getMessage("hello", null, null)).isEqualTo("안녕");
    assertThat(ms.getMessage("hello", null, Locale.KOREA)).isEqualTo("안녕");
}

 - ms.getMessage("hello", null, null) : locale 정보가 없으므로 messages 를 사용

 - ms.getMessage("hello", null, Locale.KOREA) : locale 정보가 있지만, message_ko 가 없으므로 messages 를 사용

 

MessageSourceTest 추가 - 국제화 파일 선택2

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

 - ms.getMessage("hello", null, Locale.ENGLISH) : locale 정보가 Locale.ENGLISH 이므로 messages_en 을 찾아서 사용

 

전체 테스트 결과

전체 테스트 결과

 

728x90
반응형

댓글