참치코더의 꿈 메모장

Spring / Spring Boot 메시지(MessageSource)와 국제화 정리 본문

Spring

Spring / Spring Boot 메시지(MessageSource)와 국제화 정리

참치깡 2026. 1. 26. 18:00
728x90

 

1. 메시지(Message)

 

- 스프링에서 말하는 메시지는 화면, 로그, 에러 메시지 등에 사용되는 문자열을 코드에서 분리한 것이다.

- 문자열을 코드에 하드코딩 하지 않고, properties 파일에 모아 관리하는 개념이다.

 

사용하는 이유

 

- 다국어 지원 (국제화)

- 메시지 수정 시 코드를 재배포 할 필요가 없다. 그냥 수정이 간편하다(properties 만 수정하면 다 수정된다.)

- Validation, Exception 메시지를 공통 관리할 수 있다.

 

2. MessageSource

 

- MessageSource는 메시지를 읽어오는 인터페이스이다.

- 일반 스프링 이라면 ResourceBundleMessageSource를 기본적으로 빈으로 등록해서 사용해야 하지만 

- 스프링부트를 사용한다면 MessageSource를 자동으로 실행할때 빈으로 등록해주기 때문에 그냥 사용하면 된다.

 

3. 기본 메시지 사용방법

 

 

(1) properties 등록

 

# messages.properties

hello=안녕

welcome=환영합니다.

 

(2) MessageSource 사용

 

@Autowired

MessageSource messageSource;

 

String msg = messageSource.getMessage("hello", null, null);

 

// 결과 : 안녕 

 

국제화(i18n)란?

 

국제화(Internationalization)는 사용자의 언어(Locale)에 따라 메시지를 다르게 보여주는 것

 

messages.properties (기본)
messages_ko.properties (한국어)
messages_en.properties (영어)
messages_ja.properties (일본어)

 

# messages_ko.properties
hello=안녕

 

# messages_en.properties
hello=Hello

 

Local에 따른 메시지 조회

 

messageSource.getMessage("hello", null, Locale.KOREA); // 안녕

messageSource.getMessage("hello", null, Locale.ENGLISH); // Hello

 

Locale 변경 예시 (쿠키 기반)

 

@Bean

public LocaleResolver localeResolver() {

  CookieLocaleResolver resolver = new CookieLocaleResolver();

  resolver.setDefaultLocale(Locale.KOREA);

  return resolver;

}

 

타임리프에서 메시지 사용

 

<h1 th:text="#{hello}"></h1>  ->  <h1>안녕</h1>

 

-  MessageSource는 메시지 관리의 핵심이다.

- 스프링 부트는 대부분 자동 설정 된다.

728x90
Comments