Spring Boot

[Spring Boot] 메세지, 국제화 관리 기능

수수한개발자 2022. 6. 28.
728x90

메세지 관리

HTML 화면 에서 예를들어 쇼핑몰이라고 가정했을때 상품명이라는 메세지가있다.

근데 기획자가 이걸 전부다 상품 이름으로 변경해달라고했을때 적게는 몇개에서 많게는 수백개까지의 화면의 상품명이라고 써있는 곳을 찾아서 상품이름으로 바꿀려고생각하면 물론 replaceall해서 바꿀수도있지만 

귀찮은 일이고 잘못들어가서 화면이 랜더링 안 될수도있다.

그래서 스프링에서는 이 메세지를 관리 할 수 있게 키, 벨류 형식으로 관리 할 수 있게 제공한다. 지금부터 메세지 관리 기능에 대해서 알아보겠습니다.

 

직접등록

package hello.itemservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ResourceBundleMessageSource;

@SpringBootApplication
public class ItemServiceApplication {

	public static void main(String[] args) {
		SpringApplication.run(ItemServiceApplication.class, args);
	}

	@Bean
	public MessageSource messageSource() {
		ResourceBundleMessageSource messageSource = new
				ResourceBundleMessageSource();
		messageSource.setBasenames("messages", "errors");
		messageSource.setDefaultEncoding("utf-8");
		return messageSource;
	}

}

메인 메소드에 MessageSource 인터페이스를 빈으로 등록합니다. setBasenames를 하면 messages.properties 를 읽어옵니다.

파일의 위치는 /resources/messages.properties 가 됩니다. 하지만 스프링부트를 사용하면 위와같이 직접등록하는 것이 아니라 스프링 부트가 MessageSource 를 자동으로 스프링 빈으로 등록합니다.

 

스프링부트에서 메시지 설정

application.properties이나 yml에 기본값은 아래와 같다..(application.properties 기준)

spring.messages.basename=messages

따라서 messages_en.properties , messages_ko.properties , messages.properties 파일만 등록하면 자동으로 인식된다.

영어에서 들어올때, 한국에서 들어올때, 없으면 기본값으로 들어온다.

 

그러면 설정을 해보자.

/resources/messages.properties 경로에 만들면 된다.

messages.properties

hello=안녕
hello.name=안녕 {0}

 

messages_en.properties

/resources/messages_en.properties 경로에 만들어 준다.

hello=hello
hello.name=hello {0}

영어로 들어오면 messages_en.properties 를 읽어오고 그 외 다른 것은 다 messages.properties로 읽어 들인다.

 

그래서 위와 같은 프로젝트가 구성된다. 그러면 이제 테스트를 해보자

메시지 소스 사용

package hello.itemservice.message;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.MessageSource;

import static org.assertj.core.api.Assertions.*;

@SpringBootTest
public class MessageSourceTest {

    @Autowired
    MessageSource messageSource;

    @Test
    public void helloMessage() {
        String result = messageSource.getMessage("hello", null, null);
        assertThat(result).isEqualTo("안녕");
    }
}

테스트 코드를 작성하고 돌려보자.

근데 여기서 messages.properties 의 테스트가 한글이 깨져서 나오면서 테스트가 실패하는 케이스가있다.

그럴때는 아래 경로로 들어가서 UTF-8 로 바꾸면 hello=안녕이라고 써놨던게 ??로 바뀌어져있다. 그러면 다시 안녕으로 바꾸고 테스트를 돌린다.

File >> Settings >> Editor >> File Encodings >> Global
File >> Settings >> Editor >> File Encodings >> Project Encoding

 

그럼에도 안되면 File > Invaildate Caches >> Reset을 해주자.

@Test
void argumentMessage() {
    String result = ms.getMessage("hello.name", new Object[]{"Spring"}, null);
    assertThat(result).isEqualTo("안녕 Spring");
}

위와 같이 테스트를 돌리면 hell.name = 안녕{0} 여기에 Spring!이들어가 테스트가 통과된다.

마지막 파라미터느 이제 국제화를 위한 언어를 넣어주면 된다.

 

@Test
    void defaultLang() {
        assertThat(ms.getMessage("hello", null, null)).isEqualTo("안녕");
        assertThat(ms.getMessage("hello", null, Locale.KOREA)).isEqualTo("안녕");
    }

    @Test
    void enLang() {
        assertThat(ms.getMessage("hello", null,Locale.ENGLISH)).isEqualTo("hello");
    }

이런식으로 Locale.KOREA, Locale.ENGLISH 를 넣어주면 거기에맞는 properties를 읽어와 값을 뽑아낸다.

이제 테스트를 끝냈으니 적용을 해보자.

 

메시지 적용

meesage.properties에 다음과 같이 추가를 한다.

hello=안녕
hello.name=안녕 {0}

label.item=상품
label.item.id=상품 ID
label.item.itemName=상품명
label.item.price=가격
label.item.quantity=수량

page.items=상품 목록
page.item=상품 상세
page.addItem=상품 등록
page.updateItem=상품 수정

button.save=저장
button.cancel=취소

이러고 사용할 heml에 가서 적용하면된다. 참고로 글쓴이는 thymeleaf를 사용하였다.

<h2>상품 등록 폼</h2>

위와같은 태그에서 

<h2 th:text="#{page.addItem}">상품 등록 폼</h2>

이렇게 properties에 써준 내용을 그대로 써주면 랜더링되어서 나온다.

 

국제화 적용하기

messages_en.properties에 위와같이 영어로 랜더링할 단어를 써주면 끝납니다.테스트 방법은 크롬에 언어를 영어로바꾸고 로컬서버에 들어가면 영어로 다 바뀌어져있습니다 ㅎㅎ

728x90

댓글