Notice
Recent Posts
Recent Comments
Link
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

Spring 메시지 소스 활용 본문

인프런/[인프런] 스프링 MVC 2

Spring 메시지 소스 활용

Seung__ 2021. 9. 24. 13:06

1. 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;
}
  • code와 일부 파라미터로 메세지를 읽어올 수 있는 기능을 제공

 

 

2. 예시-기본


  • 앞서 messages.properties에 아래와 같이 등록했다.
  • 여기서 hello는 code, 안녕은  message 이다.
hello=안녕
hello.name=안녕 {0}
  • 메시지 기능을 사용하기 위해 아래와 같이 test를 작성
    • @Autowired를 통해 스프링 빈으로 등록된 messageSource를 가져옴.
    • getMessge(code, args, locale) 를 사용하여 message를 가져올 수 잇다.
@SpringBootTest
public class MessageSourceTest {

    @Autowired
    MessageSource ms;

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

 

 

 

3. MessageSource를 찾지 못한 경우


  • MessageSource를 찾지 못하면 NoSuchMessageException이 발생.
    @Test
    void notFoundMessageSource(){
        assertThatThrownBy(() -> ms.getMessage("no_code", null, null))
                .isInstanceOf(NoSuchMessageException.class);
    }
  • MessageSource를 찾기 못한 경우 defaultMessage를 반환할 수 있다.
    @Test
    void notFoundMessageSourceReturnDefaultMessage(){
        String result = ms.getMessage("no_code", null, "기본 메시지", null);
        assertThat(result).isEqualTo("기본 메시지");
    }

 

 

 

4. 매개변수 사용


  • 앞서 messages.properties에 매배변수도 추가했다.
hello=안녕
hello.name=안녕 {0}
  • hello.name의 경우 {0}은 getMessage()에서 넘겨주는 Obejct의 배열의 해당 index에 해당하는 값으로 치환된다.
    @Test
    void argumentMessage(){
        String message = ms.getMessage("hello.name", new Object[]{"Spring"}, null);
        assertThat(message).isEqualTo("안녕 Spring");
    }

  • 따라서 code가 hello.name인 메시지를 불러올 때 args로 Spring을 넘겨주면,
  • "안녕 Spring"으로 치환된다.

 

 

 

5. 국제화


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

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

 

 

6. GitHub : 210924 message, Lang


 

GitHub - bsh6463/Thymeleaf_Message

Contribute to bsh6463/Thymeleaf_Message development by creating an account on GitHub.

github.com

 

'인프런 > [인프런] 스프링 MVC 2' 카테고리의 다른 글

WebApplication 국제화 적용  (0) 2021.09.24
WebApplication에 메시지 적용  (0) 2021.09.24
Spring 메시지 소스 설정  (0) 2021.09.24
[Thymealef] 메시지, 국제화  (0) 2021.09.24
select box  (0) 2021.09.23
Comments