스프링이 메시지와 국제화 기능을 모두 제공한다.
메시지 소스 설정하기
spring.messages.basename=messages,config.i18n.messages
MessageSource를 스프링 빈으로 등록하지 않으면 message라는 이름으로 기본 등록된다. 따라서 message_en.properties와 같이 파일만 등록하면 자동인식이 된다.
<테스트를 위한 message.properties, message_en.properties>
hello=안녕
hello.name=안녕 {0}
hello=hello
hello.name=hello {0}
<테스트 클래스 MessageSourceTest>
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 ms;
@Test
void helloMessage(){
String result = ms.getMessage("hello",null,null);
assertThat(result).isEqualTo("안녕");
}
@Test
void notFoundMessageCode(){
assertThatThrownBy(()->ms.getMessage("no_code",null,null))
.isInstanceOf(NoSuchMessageException.class);
}
@Test
void notFoundMessageCodeDefaultCode(){
String result = ms.getMessage("no_code",null,"기본 메시지",null);
assertThat(result).isEqualTo("기본 메시지");
}
@Test
void argumentMessage(){
String message = ms.getMessage("hello.name",new Object[]{"Spring"},null);
assertThat(message).isEqualTo("안녕 Spring");
}
@Test
void deaultLang(){
assertThat(ms.getMessage("hello",null,null)).isEqualTo("안녕");
assertThat(ms.getMessage("hello",null, Locale.KOREA)).isEqualTo("안녕");
}
@Test
void enLang(){
assertThat(ms.getMessage("hello",null,Locale.ENGLISH)).isEqualTo("hello");
}
}
@Test
void deaultLang(){
assertThat(ms.getMessage("hello",null,null)).isEqualTo("안녕");
assertThat(ms.getMessage("hello",null, Locale.KOREA)).isEqualTo("안녕");
}
ms.getMessage("hello", null, null) : locale 정보가 없으므로 messasge를 사용함
ms.getMessage("hello", null, Locale.KOREA) : locale 정보가 있지만, 를 사용 message_ko가 없으므로 message를 사용
@Test
void enLang(){
assertThat(ms.getMessage("hello",null,Locale.ENGLISH)).isEqualTo("hello");
}
ms.getMessage("hello", null, Locale.ENGLISH) : locale 정보가 Locale.ENGLISH이므로 messages_en 을 찾아서 사용
'BackEnd > spring' 카테고리의 다른 글
검증(직접 처리) (0) | 2024.07.25 |
---|---|
웹 애플리케이션에 국제화 적용하기 (0) | 2024.07.24 |
간단한 Web페이지 프로젝트(7) - RedirectAttributes (0) | 2024.07.07 |
간단한 Web페이지 프로젝트(6) - PRG Post/Redirect/Get (0) | 2024.07.07 |
간단한 Web페이지 프로젝트(5) - 상품 수정 (0) | 2024.07.06 |