IoC Container - MessageSource

| MessageSource

  • Application 을 다국화 하는 방법을 제공하는 인터페이스이다.
  • ApplicationContext는 MessageSource 인터페이스를 상속하고 있다.
  • SpringBoot 에서는 기본적으로 message.properties 를 활용한다

파일 네이밍 규칙에 따라 자동으로 언어를 교환한다.

  • 한국어 : message_ko.properties
  • 영어 : message_en.properties

 

예제

먼저 Default를 살펴보자.

@Component
public class AppRunner implements ApplicationRunner {

    @Autowired
    MessageSource messageSource;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(messageSource.getClass());
        System.out.println(Locale.ENGLISH);
        System.out.println(Locale.KOREAN);
        System.out.println(Locale.KOREA);
    }
}
class org.springframework.context.support.ResourceBundleMessageSource
en
ko
ko_KR

 

각 언어 파일을 생서해보자

  • messages.properties : hello=hello basic
  • messages_en.properties : hello EN
  • messages_ko.properties : hello ko

참고로 messages_ko.properties 파일이 없다면 기본 프로퍼티인 messages.properties를 따라 간다

 

@Component
public class AppRunner implements ApplicationRunner {

    @Autowired
    MessageSource messageSource;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        System.out.println(messageSource.getMessage("hello", null, Locale.getDefault()));
        System.out.println(messageSource.getMessage("hello", null, Locale.KOREAN));
        System.out.println(messageSource.getMessage("hello", null, Locale.KOREA));
        System.out.println(messageSource.getMessage("hello", null, Locale.ENGLISH));
    }
}
  • getMessages는 MessageSource에 해당하는 Key를 가져온다.
  • getMessage의 매개변수는 message_key, args, Locale 순서이다.
    • hello=안녕, {0}, {1} 으로 설정하면 args을 순서대로 {0},{1} 넣으면 된다.

결과

hello ko
hello ko
hello ko
hello EN

 

댓글

Designed by JB FACTORY