728x90
기본 메시지 기능 V1
- 기능
- 스프링 부트에 메시지 파일 등록
- locale 정보에 따른 국제화 기능 구현
깃 : https://github.com/kureungkureung/basicMessage-V1-/tree/master#basicmessage-v1
1. 메시지 파일 기능
🔍 메시지 파일 생성하기
📌 /resources/messages.properties
hello=GoodGood
hi=hiYo {0}
메시지 파일을 작성하였다. key=value 형태로 작성하면 된다. 그래서 key 값을 통해 value 값을 호출하는 것이다. 두 번째 메시지에 {0} 처럼 파라미터를 넣을 수도 있다.
🔍 스프링 부트에서 메시지 파일 등록하기
📌 application.properties
spring.messages.basename=messages
application.properties 파일에 파일명을 적어주면 된다. 스프링 부트는 messages.properties 파일인 메시지 파일에 대하여 기본적으로 등록이 되어있어 messages 파일 등록은 생략해도 된다.
🔍 뷰에 적용하기
📌 home.html
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p th:text="#{hello}"></p>
</body>
</html>
타임리프의 문법인 #{...} 을 사용하여 메시지 파일에 적힌 메시지를 렌더링 했다.
2. 국제화 기능
🔍 국제화 메시지 파일 생성하기
기본 메시지 파일명은 messages.properties로 해놓고 영어권 메시지 파일은 messages_en.properties로 만든다. locale 정보에 따라 영어권 메시지 파일이 적용될지, 기본 메시지 파일이 적용될지 결정된다.
3. 테스트 코드
package hello.basicmessage;
@SpringBootTest
public class MessageTest {
@Autowired
MessageSource ms;
@Test
void 기본메시지테스트() {
String hello = ms.getMessage("hello", null, null);
assertThat(hello).isEqualTo("굳굳");
}
@Test
void 영어메시지테스트() {
String hello = ms.getMessage("hello", null, Locale.ENGLISH);
assertThat(hello).isEqualTo("GoodGood");
}
@Test
void 기본메시지파라미터() {
String hi = ms.getMessage("hi", new Object[]{"쿵쿵따"}, null);
assertThat(hi).isEqualTo("안녕 쿵쿵따");
}
@Test
void 기본영어메시지파라미터() {
String hi = ms.getMessage("hi", new Object[]{"tori"}, Locale.ENGLISH);
assertThat(hi).isEqualTo("hiYo tori");
}
}
스프링 부트는 MessageSource 인터페이스가 자동으로 등록이 되어있다. MessageSource를 이용하여 메세지 기능 테스트와 locale 정보를 주고 국제화 기능 테스트 코드를 구현했다.
v2 버전 : https://terry9611.tistory.com/304?category=931905
728x90
'[ Spring ] > Spring Toy' 카테고리의 다른 글
[Spring] 기본 메시지 기능 V2 - 다양한 LocaleResolver 구현을 통한 국제화 기능 구현 (0) | 2022.04.18 |
---|