해당 게시물은 백기선님의 스프링 프레임워크 핵심 기술 강좌를 정리한 내용 입니다.
MessageSource
- 국제화(i18n) 기능을 제공하는 인터페이스 입니다.
- ApplicationContext가 MessageSource 인터페이스를 상속 받는다.
- ApplcationContext를 주입 받는 것처럼, MessageSource도 주입을 받을 수 있다.
MessageSource - 예제
1) resources 아래에 각 국가에 맞는 메시지 설정 파일을 생성 합니다.
[messages.properties]
# message.properties
greeting = Hello, {0}
[messages_ko_KR.properties]
# message_ko_KR.properties
greeting = 안녕, {0}
2) AppRunner 클래스에서 아래와 같은 코드를 작성한다.
@Component
public class AppRunner implements ApplicationRunner {
@Autowired
MessageSource messageSource;
@Override
public void run(ApplicationArguments args) throws Exception {
// 이미 등록 되어 있는 Bean이 어떠한 클래스 인지 확인
System.out.println(messageSource.getClass());
Locale.setDefault(new Locale("en","US"));
// 로케일이 Locale.US 이므로 "messages_en_US" 파일을 읽는다.
System.out.println(messageSource.getMessage("greeting", new String[]{"keesun"}, Locale.KOREA));
// 한국은 기본 로케일이 Locale.KOREA 이므로 "messages_ko_KR" 파일을 읽는다.
System.out.println(messageSource.getMessage("greeting", new String[]{"keesun"}, Locale.getDefault())); // 기본 로케일
}
}
[실행 결과]
리로딩 기능이 있는 메시지 소스 사용하기
MessageSource의 구현체로 ReloadableResourceBundleMessageSource를 사용하면 애플리케이션 실행 중에
메시지를 리로드하여 변경사항을 적용할 수 있다.
① MessageSource 빈을 정의 합니다.
@SpringBootApplication
public class Demospring51Application {
public static void main(String[] args) {
SpringApplication.run(Demospring55Application.class, args);
}
@Bean
public MessageSource messageSource(){
var messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:/messages");
messageSource.setDefaultEncoding("UTF-8");
messageSource.setCacheSeconds(3); // 3초 마다 메시지를 다시 읽는다. (최대 3초까지 캐싱을 하고 다시 읽음)
return messageSource;
}
}
② 1초 마다 메시지를 읽어 출력하도록 합니다.
@Component
public class AppRunner implements ApplicationRunner {
@Autowired
MessageSource messageSource;
@Override
public void run(ApplicationArguments args) throws Exception {
while(true){
Locale.setDefault(new Locale("en","US"));
System.out.println(messageSource.getMessage("greeting", new String[]{"keesun"}, Locale.KOREA));
System.out.println(messageSource.getMessage("greeting", new String[]{"keesun"}, Locale.getDefault()));
Thread.sleep(1000l);
}
}
}
③ 애플리케이션 실행 도중 message.properties와 message_ko_KR.properties의 값을 변경한 다음, Build를 하면
메시지가 리로드 되는 것을 확인 할 수 있습니다.
'Spring > Spring Core' 카테고리의 다른 글
[Section 1] IoC 컨테이너 9부: ResourceLoader (0) | 2020.09.06 |
---|---|
[Section 1] IoC 컨테이너 8부: ApplicationEventPublisher (0) | 2020.09.06 |
[Section 1] IoC 컨테이너 6부: Environment 2부. 프로퍼티 (0) | 2020.09.03 |
[Section 1] IoC 컨테이너 6부: Environment 1부. 프로파일 (0) | 2020.09.03 |
[Section 1] IoC 컨테이너 5부: 빈의 스코프(Scope) (0) | 2020.09.03 |
댓글