본문 바로가기
프로그래밍/스프링프레임워크

Java Config로 메세지소스(MessageSource) 설정하기(다국어 지원)

by pentode 2019. 3. 19.

스프링프레임워크에서 다국어지 지원을 위한 메세지소스 설정을 Java Config로 해 봅니다. 이번 예제는 "Spring Framework 메세지 국제화(다국어 지원) 사용하기" 에서의 xml 설정을 Java 클래스를 사용한 설정으로 변경한 것입니다. MessageSource의 사용법은 이글을 참조 하세요. 전체 예제소스는 글의 끝에 첨부해 두었습니다.



1. 메세지소스를 생성하는 설정 클래스를 작성합니다.


MessageSource 와 언어 변경에 사용될 Locale Resolver를 생성합니다. 여기서는 언어정보를 세션에 저장하도록 SessionResolver를 생성합니다.


package com.tistory.offbyone.init;


import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.support.ReloadableResourceBundleMessageSource;

import org.springframework.web.servlet.i18n.SessionLocaleResolver;


/**

 * 메세지 소스 설정

 */

@Configuration

public class ContextMessage {

/**

* 메세지 소스를 생성한다.

*/

@Bean

    public ReloadableResourceBundleMessageSource messageSource() {

ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource();

// 메세지 프로퍼티파일의 위치와 이름을 지정한다.

        source.setBasename("classpath:/messages/message");

        // 기본 인코딩을 지정한다.

        source.setDefaultEncoding("UTF-8");

        // 프로퍼티 파일의 변경을 감지할 시간 간격을 지정한다.

        source.setCacheSeconds(60);

        // 없는 메세지일 경우 예외를 발생시키는 대신 코드를 기본 메세지로 한다.

        source.setUseCodeAsDefaultMessage(true);

        return source;

    }


/**

* 변경된 언어 정보를 기억할 로케일 리졸퍼를 생성한다.

* 여기서는 세션에 저장하는 방식을 사용한다.

* @return

*/

@Bean

public SessionLocaleResolver localeResolver() {

return new SessionLocaleResolver();

}

}


2. 메세지 프로퍼티 파일 입니다.


위 설정에 따라 클래스패스 아래에 위치하므로 /WEB-INF/classes/messages/message.properties 파일이 됩니다.


site.title=스프링 테스트 사이트

site.count={0} 테스트 사이트 입니다.

msg.first=첫번째


3. Web 컨텍스트 설정에 언어 변경 처리를 위한 인터셉터를 생성하여 등록합니다.


WebContextConfiguration.java 파일에 추가합니다.


/**

 * 언어 변경을 위한 인터셉터를 생성한다.

 */

@Bean

public LocaleChangeInterceptor localeChangeInterceptor() {

LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();

interceptor.setParamName("lang");

return interceptor;

}


/**

 * 인터셉터를 등록한다.

 */

@Override

public void addInterceptors(InterceptorRegistry registry) {

    registry.addInterceptor(localeChangeInterceptor());

}


4. 컨트롤러에서 메세지 소스를 사용해봅니다.

@Autowired

MessageSource messageSource;


@Autowired

LocaleResolver localeResolver;


@RequestMapping(value = "/main/i18n.do", method = RequestMethod.GET)

public String i18n(Locale locale, HttpServletRequest request, Model model) {


    // RequestMapingHandler로 부터 받은 Locale 객체를 출력해 봅니다.

    model.addAttribute("clientLocale", locale);


    // localeResolver 로부터 Locale 을 출력해 봅니다.

    model.addAttribute("sessionLocale", localeResolver.resolveLocale(request));


    // JSP 페이지에서 EL 을 사용해서 arguments 를 넣을 수 있도록 값을 보낸다.

    model.addAttribute("siteCount", messageSource.getMessage("msg.first", null, locale));


    return "main/i18n";

}


5. 메세지 소스를 사용하는 i18n.jsp 페이지 입니다.


not.exist 코드는 존재하지 않으므로 default text를 주지 않으면 예외가 발생하는  대신에 코드 값이 보여집니다.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title><spring:message code="site.title" text="스프링 테스트 사이트 - default" /></title>

</head>


<body>

<p>

<a href="<c:url value='/main/i18n.do?lang=ko' />">한국어</a>

<a href="<c:url value='/main/i18n.do?lang=en' />">English</a>

</p>

<p>site.title : <spring:message code="site.title" text="default text" /></p>

<p>site.count : <spring:message code="site.count" arguments="첫번째" text="default text" /></p>

<p>site.count using EL : <spring:message code="site.count" arguments="${siteCount}" text="default text" /></p>

<p>not.exist : <spring:message code="not.exist" /></p>

<p>Client Locale : <c:out value="${clientLocale}" /></p>

<p>Session Locale : <c:out value="${sessionLocale}" /></p>

</body>

</html>


6. 실행결과 입니다.


실행결과


※ 전체 예제소스




반응형