IoC Container - MessageSource
- 📚 Spring/Spring 개념
- 2020. 9. 11. 09:39
| 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
'📚 Spring > Spring 개념' 카테고리의 다른 글
IoC Container - ResourceLoader (0) | 2020.09.11 |
---|---|
IoC Container - ApplicationEventPublisher (0) | 2020.09.11 |
IoC 컨테이너 - Environment (0) | 2020.09.09 |
IoC 컨테이너 - Bean 의 스코프(Scope) (0) | 2020.09.09 |
@Component와 Component Scan (0) | 2020.09.01 |