프로그램 자료/Java & Spring

[Spring] 다국어 메시지 콘트롤러에서 접근 message.properties access in controller

motolies 2018. 7. 13. 13:20

출처1 : http://g00glen00b.be/spring-internationalization-i18n/

출처2 : https://stackoverflow.com/questions/11392692/autowired-in-static-classes


[환경]

spring boot 2.0.3


[내용]

thymeleaf에서 시작 태그와 닫는 태그가 일치 하지 않는 출력 해야 할 일이 생겼다. 

(일 단위 리스트를 주 단위로 출력해야 하는 것)


thymeleaf 는 xml 형식이라 시작 태그와 닫는 태그가 일치해야 오류가 나지 않더라.


그래서 결국엔 아래와 같은 형식으로 태그 문자열을 콘트롤러에서 받아서 찍었다. 

<th:block th:if="${condition}" th:utext="${modelAndView.data}" ></th:block>


그런데, 다국어를 지원해야하다보니 thymeleaf에서 문자열로 찍는 #{message}에서는 다국어 지원을 하지 않아서 

콘트롤러에서 메시지 가져와 변환하도록 했다. 


다음은 static method로 만든 메시지 접근 클래스이다. 




import javax.annotation.PostConstruct;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.MessageSource;

import org.springframework.context.i18n.LocaleContextHolder;

import org.springframework.stereotype.Component;

 

@Component

public class MessageHelper {

 

    private static MessageSource messageSource;

 

    @Autowired

    private MessageSource initMessageSource;

 

    @PostConstruct

    private void initStaticDao() {

        //https://stackoverflow.com/questions/11392692/autowired-in-static-classes

        messageSource = this.initMessageSource;

    }

 

    public static String getMessage(String code) {

        return messageSource.getMessage(code, null, LocaleContextHolder.getLocale());

    }

 

    public static String getMessage(String code, String defaultString) {

        return messageSource.getMessage(code, null, defaultString, LocaleContextHolder.getLocale());

    }

 

}