메시지 소스 설정 ( 스프링 빈 등록 )
스프링 웹 프레임워크는 메시지의 기본적인 관리 기능을 제공한다.
해당 기능을 사용하기 위해서는 스프링에서 제공되는 인터페이스인 MessageSource 를 스프링 빈으로 등록하는 과정이 필요하다.
그에 따라 이러한 인터페이스의 구현체인 ResourceBundleMessageSource 를 스프링 빈으로 등록한다.
1. 직접 등록
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasenames("messages", "errors");
messageSource.setDefaultEncoding("utf-8");
return messageSource;
}
- messageSource.setBasenames("messages", "errors")
- "messages" : messgaes.properties 파일을 읽어 사용
- 추가적으로 국제화 기능 적용이 필요할 경우 messages_en.properties 와 같은 네이밍 (국제화 파일을 찾을 수 없다면 messgaes.properties 를 기본으로 사용
- 메시지 및 국제화 파일의 위치 : /resources/messages.properties
- 한 번에 여러 파일을 한 번에 지정 가능 : ex) ("messages", "errors") - messageSource.setDefaultEncoding("utf-8")
- 인코딩 정보 지정 ( "utf-8" )
2. 스프링 부트 등록
스프링 부트는 해당 MessageSource의 스프링 빈을 자동으로 등록한다.
스프링 부트 메시지 소스 설정
application.properties
spring.messages.basename=messages,config.i18n.messages
- spring.messages.basename=messages
- MessageSource 의 별도 스프링 빈 등록 및 설정을 하지 않으면, messages 의 이름으로 기본 등록
- 그 외 messages_en, messages_ko 파일 등 등록 시 자동 인식
메시지 만들기
아래에서 메시지, 국제화 기능 테스트에 사용될 메시지 파일을 만든다.
- messages.properties : 기본 값으로 사용 (한글) (message가 아닌 messages의 오타에 주의)
- messages_en.properties : 영어 지원을 위한 국제화에 사용
messages.properties ( /resources/messages.properties )
hello=안녕
hello.name=안녕 {0}
messages_en.properties ( /resources/messages_en.properties )
hello=hello
hello.name=hello {0}
메시지 소스 사용
MessageSource interface
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 인터페이스를 보면 알 수 있듯 코드를 포함한 일부 파라미터로 메시지 읽어오기 기능을 제공한다.
MessageSourceTest - Class
@SpringBootTest
public class MessageSourceTest {
@Autowired MessageSource ms;
@Test
void helloMessage() {
String result = ms.getMessage("hello", null, null);
assertThat(result).isEqualTo("안녕");
}
}
- ms.getMessage("hello", null, null)
- code : "hello" → 메시지 코드
- args : null
- locale : null → locale 정보가 없을 시 basename에서 설정한 기본 메시지 파일 조회
MessageSourceTest - TestCode (메시지 부재, 기본 메시지)
@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 - TestCode ( 매개변수 사용)
@Test
void argumentMessage() {
String result = ms.getMessage("hello.name", new Object[]{"Spring"}, null);
assertThat(result).isEqualTo("안녕 Spring");
}
- 메시지 설정 파일 (messages.properties)의 {0} 부분은 매개변수 전달을 통해 치환 가능
- hello.name=안녕 {0} → Spring 단어 매개변수 전달 → '안녕 스프링'
국제화 파일 선택
- locale 정보 기반으로 국제화 파일 선택
- Locale 정보가 en_US 의 경우 messages_en_US → messages_en → messages 순으로 탐색
(구체적으로 설정된 메시지 파일을 우선적으로 선택)
MessageSourceTest - TestCode (기본 메시지)
@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 정보가 있지만, messages_ko 파일을 설정하지 않았으니 messages 파일 사용 (기본 메시지 파일)
MessageSourceTest - TestCode (국제화 파일)
@Test
void enLang() {
assertThat(ms.getMessage("hello", null, Locale.ENGLISH)).isEqualTo("hello");
}
- ms.getMessage("hello", null, Locale.ENGLISH) : locale 정보가 설정되어 있으니 Locale.ENGLISH에 맞는 messages_en 파일을 찾아 사용
'Spring' 카테고리의 다른 글
[Spring] 메시지, 국제화 소개 (0) | 2023.03.13 |
---|---|
[Spring] 초기 프로젝트 설정 (재고 관리 서비스) (0) | 2023.03.10 |