본문 바로가기

Study Information Technology

Spring Boot의 국제화i18n 지원 이해하기

728x90
반응형

Spring Boot의 국제화(i18n) 지원 이해하기

Overview

Spring Boot는 국제화(i18n)를 지원하여 다양한 언어와 지역을 위해 애플리케이션을 쉽게 개발할 수 있도록 합니다. 이 기능은 사용자 경험을 향상시키고 글로벌 시장에 진출하는 데 필수적입니다. 이번 글에서는 Spring Boot의 국제화 지원을 구체적으로 설명하고, 설정 방법과 함께 실제 예제를 통해 어떻게 구현할 수 있는지 살펴보겠습니다.

1. 국제화(i18n)란 무엇인가?

국제화(i18n)는 소프트웨어가 다양한 언어와 문화적 맥락에 맞게 조정될 수 있도록 하는 프로세스입니다. 이를 통해 애플리케이션은 사용자의 언어, 지역, 날짜 형식, 숫자 형식 등을 고려하여 표시됩니다.

2. Spring Boot에서의 국제화 지원

Spring Boot는 국제화를 지원하기 위해 MessageSource 인터페이스와 LocaleResolver를 사용합니다. 이를 통해 애플리케이션의 메시지를 다양한 언어로 제공할 수 있습니다.

2.1. 메시지 소스(MessageSource)

메시지 소스는 특정 로케일에 따라 적절한 메시지를 반환하는 역할을 합니다. 기본적으로 Spring Boot는 messages.properties 파일을 사용하여 메시지를 관리합니다.

예를 들어, messages.properties 파일에 다음과 같은 내용을 추가할 수 있습니다.

greeting=안녕하세요
farewell=안녕히 가세요

이 파일은 기본 언어(일반적으로 영어)로 사용됩니다. 다른 언어를 추가하려면 messages_ko.properties, messages_en.properties와 같은 파일을 생성하여 해당 언어로 번역된 메시지를 입력할 수 있습니다.

# messages_en.properties
greeting=Hello
farewell=Goodbye

2.2. 로케일 해석기(LocaleResolver)

로케일 해석기는 사용자의 로케일을 결정하는 역할을 합니다. Spring Boot에서는 LocaleChangeInterceptor를 사용하여 URL 파라미터를 통해 로케일을 변경할 수 있습니다.

3. Spring Boot에서 국제화 설정하기

국제화 설정은 몇 가지 단계로 진행됩니다.

3.1. 의존성 추가

Spring Boot 애플리케이션에서는 기본적으로 국제화 기능이 포함되어 있지만, Maven을 사용하는 경우 spring-boot-starter-web 의존성을 추가해야 합니다.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

3.2. 메시지 소스 파일 생성

src/main/resources 디렉터리에 messages.properties, messages_ko.properties, messages_en.properties 파일을 생성하여 각각의 언어에 맞는 메시지를 정의합니다.

3.3. WebMvcConfigurer 구현

WebMvcConfigurer를 구현하여 국제화 설정을 추가할 수 있습니다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

import java.util.Locale;

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver resolver = new CookieLocaleResolver();
resolver.setDefaultLocale(Locale.KOREAN);
return resolver;
}

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("lang");
return interceptor;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}

이 설정은 기본적으로 한국어를 설정하고, URL 파라미터를 통해 언어를 변경할 수 있도록 합니다. 예를 들어, ?lang=en을 URL에 추가하면 영어로 변경됩니다.

4. 컨트롤러와 뷰에서의 메시지 사용

이제 컨트롤러와 뷰에서 메시지를 사용할 수 있습니다.

4.1. 컨트롤러에서 메시지 사용

Spring의 MessageSource를 주입받아 메시지를 가져올 수 있습니다.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Locale;

@RestController
public class GreetingController {

@Autowired
private MessageSource messageSource;

@GetMapping("/greet")
public String greet(@RequestParam(name = "lang", required = false) String lang, Locale locale) {
if (lang != null) {
locale = new Locale(lang);
}
return messageSource.getMessage("greeting", null, locale);
}
}

4.2. 뷰에서 메시지 사용

Thymeleaf와 같은 템플릿 엔진을 사용하는 경우, 다음과 같이 메시지를 참조할 수 있습니다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Greeting</title>
  </head>
  <body>
    <h1 th:text="#{greeting}">Hello</h1>
    <p th:text="#{farewell}">Goodbye</p>
  </body>
</html>

5. 에러 처리

국제화 설정 중에 문제가 발생할 수 있습니다. 예를 들어, 잘못된 로케일을 요청하면 NoSuchMessageException이 발생할 수 있습니다. 이 경우, 다음과 같이 에러를 처리할 수 있습니다.

import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@ControllerAdvice
public class GlobalExceptionHandler extends DefaultHandlerExceptionResolver {

@ExceptionHandler(NoSuchMessageException.class)
public String handleNoSuchMessage(NoSuchMessageException e, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("error", "메시지를 찾을 수 없습니다: " + e.getMessage());
return "redirect:/error";
}
}

6. 결론

Spring Boot의 국제화(i18n) 기능을 통해 다양한 언어로 애플리케이션을 개발할 수 있습니다. 기본적인 메시지 소스 설정부터 로케일 해석기, 컨트롤러 및 뷰에서의 메시지 사용까지, 각 단계별로 잘 설정하면 글로벌 사용자에게 맞춤형 경험을 제공할 수 있습니다.

이러한 국제화 기능은 사용자가 선택한 언어에 따라 적절한 메시지를 보여주며, 다국적 시장에 진출하는 데 도움을 줄 수 있습니다.

참고문서

반응형