Spring MessageSource 국제화


Spring MessageSource 사용


Spring에서는 MessageSource 관련 구현체를 ApplicationContext에서 지원한다. 설정파일에서 MessageSource를 구현체를 등록하는 간단한 bean정의만 완료하면 ApplicationContext에 접근하여 원하는 메시지를 얻어 오는게 가능하다. 정의한 MessageSource bean을 직접 획득하여 사용하는 것도 가능하지만 ApplicationContext에서 자동지원 하는 방식을 이용하는 쪽이 추후에 Spring MVC 패턴 등에 사용되어 사용성이 좋다고 한다.


MessageSource 구현체

  • org.springframework.context.support.ResourceBundleMessageSource

ResourceBundle 클래스와 MessageFormat클래스 기반으로 만들어 졌으며, 번들에 특정 이름으로 접근가능.


  • org.springframework.context.support.ReloadableResourceBundleMessageSource

<property name="cacheSeconds" value="5"/> 프로퍼티 설정으로 reloading 하여 application 실행 와중에 번들 변경이 가능하다.


  • org.springframework.context.support.StaticMessageSource

MessageSource의 가장 간단한 구현체로 기본적인 국제화를 지원하면 테스트 용도로 만들어짐.



위에 세 가지가 Spring에서 지원하는 MessageSource 구현체로 위의 Class에 대한 bean을 정의하면 ApplicationContext접근을 통하여 대상 메시지를 출력할 수 있다. 이 중 ReloadableResourceBundleMessageSource는 메시지 내용을 캐시하여 가지고 있으며 인터벌을 지정하여 초단위 간격으로 메시지 파일을 재로딩 하여 어플리케이셔 종료 없이 properties 파일 수정으로 메시지 값 변경이 가능하다.


사용방법

  1. 위에 세 가지 MessageSource 구현체를 bean으로 등록한다. 
  2. 이 때 id="messageSource"로 지정하는 것 을 명심 (그렇지 않으면 동작하지 않음)
  3. 이 후 ApplicationContext.getMessage() 메소드로 메시지 획득


Example


[app-context.xml]

bean의 id는 반드시 messageSource

bean의 class는 MessageSource 구현체 이여야 한다.

한글 출력을 하는 경우 defaultEncoding을 지정하도록 하자.

위와 같이 bean만 등록만 해두면 별도의 설정은 필요없다.

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
31
32
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.2.xsd">
    
    <bean id = "messageSource" 
        class="org.springframework.context.support.StaticMessageSource" >
 
        <!-- 한글출력을 위해 Encoding 지정 -->
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
        
        <!-- List이기 대문에 복수 등록이 가능하다. -->        
        <property name="basenames">
            <list>
                <value>labels</value>
            </list>
        </property>
    </bean>
     
</beans>
 
cs


참고사항


basenames 프로퍼티 지정시 list형이기 때문에 복수 등록이 가능하다.

입력된 값에 따라서 {입력값}_{Locale}.properites 의 파일에서 번들을 등록한다.

예시) <value>labels</<value> => labels_ko_KR.propertieslabels_en_US.properties


만약, Locale을 입력하지 않은 label.properties가 있다면 default로 사용된다.

root폴더는 /src/main/resource/ 로 간주하기 때문에  대상폴더 하위에 .properties 파일이 존재하여야 한다.





[project 파일구조]

/src/main/resources 하위에 properties파일을 위치해 놓았다.


[ label_ko_KR.Properties ]

{0}과 {1}은 메시지 출력시 변수처리 될 부분이다. String 배열을 입력받아 메시지를 완성한다.

1
2
HI=안녕하세요
MSG={0} {1} 뿌잉뿌잉
cs



[ label_en_US.Properties ]

1
HI=Hello Message
cs



[MainApplication Class]

입력한 Locale에 따라 정확히 메시지가 출력된다.

23번째 라인에서 getMessage() 두번 째 인자로 String 배열이 넘어가 {0}과 {1}이 변수처리 되었다.

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
31
32
33
import java.util.Locale;
 
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.context.support.ResourceBundleMessageSource;
 
public class MainApplication {
 
    public static void main(String[] args) {
        
        GenericXmlApplicationContext appCtx = new GenericXmlApplicationContext();
        appCtx.load("classpath:META-INF/spring/app-context.xml");
        appCtx.registerShutdownHook();
        appCtx.refresh();
        
        /********************************************
         * ApplicationContext에서 자동으로 messageSource 접근
         ********************************************/
        // Locale에 따라 다른 메시지 출력 확인
        System.out.println("ko_KR HI : " + appCtx.getMessage("HI"null, Locale.KOREA ));
        System.out.println("en_US HI : " + appCtx.getMessage("HI"null, Locale.US));
        
        // 메시지 출력시 변수처리 확인
        System.out.println("변수처리 : " + appCtx.getMessage("MSG"new String[]{"삼성""갤럭시 태블릿"}, Locale.KOREA));
        
        /********************************************
         * 직접 bean을 획득하여 메시지 확인
         ********************************************/
        ResourceBundleMessageSource message =  (ResourceBundleMessageSource) appCtx.getBean("messageSource");
        System.out.println("messageSource 직접 접근 : "+ message.getMessage("HI"null, Locale.KOREA));
        
    }
    
}
cs

 


수행결과

ko_KR HI : 안녕하세요

en_US HI : Hello Message

변수처리 : 삼성 갤럭시 태블릿 뿌잉뿌잉

messageSource 직접 접근 : 안녕하세요



다운로드

SpringMessgaeSource.zip


'프로그래밍 > Spring FWK' 카테고리의 다른 글

Spring Resource  (1) 2016.01.10
Spring ApplicationEvent  (0) 2016.01.10
Spring CustomPropertyEditor  (2) 2016.01.05
Spring PropertyEditor  (0) 2016.01.05
Spring facoty-bean, factory-method  (0) 2015.12.30
Spring FactoryBean Interface  (0) 2015.12.29
Spring ApplicationContextAware Interface  (0) 2015.12.28
Spring BeanNameAware Interface  (1) 2015.12.28

이 글을 공유하기

댓글

Email by JB FACTORY