[Spring] MessageSource
in Tech-Stack on Spring
MessageSource
โ์ด๋ฉ์ผโ ๊ฐ์ด ์ฌ๋ฌ ํ์ด์ง์์ ํผ์์ ๋ฐ๋ณต์ ์ผ๋ก ์ฌ์ฉ๋๋ ๋ฌธ์์ด์ด ์กด์ฌํ๋ค๊ณ ๊ฐ์ ํ์.
๋ฌธ์์ด์ โemailโ๋ก ๋ณ๊ฒฝํด์ผ ํ ๊ฒฝ์ฐ ๋ชจ๋ ํผ์์ ๋์ผํ๊ฒ ์์ ํด์ผํ๋ ๋ฒ๊ฑฐ๋ก์์ด ์๋ค.
์ด๋ฐ ์ํฉ์ ํจ์จ์ ์ผ๋ก ํด๊ฒฐํ๊ธฐ ์ํด MessageSource๋ฅผ ์ฌ์ฉํ๋ค.
step 1. properties ํ์ผ ์์ฑ
src/main/resources์ message ํด๋๋ฅผ ๋ง๋ ํ label.properties๋ฅผ ๋ค์๊ณผ ๊ฐ์ด ์์ฑํ๋ค.
member.register=ํ์๊ฐ์
next.btn=๋ค์๋จ๊ณ
member.info=ํ์์ ๋ณด
email=์ด๋ฉ์ผ
name=์ด๋ฆ
password=๋น๋ฐ๋ฒํธ
password.confirm=๋น๋ฐ๋ฒํธ ํ์ธ
register.btn=๊ฐ์
์๋ฃ
register.done=<strong>{0} {1}๋</strong> ํ์ ๊ฐ์
์ ์ถํํฉ๋๋ค.
key=valueํ์์ผ๋ก ์ ๋ ฅํ๋ค.register.done- MessageSource์
getMessage()๊ฐ ์๋์ผ๋ก ์ ์ฉ๋๋ค. - {0}์ ์ ๋ฌ๋ฐ์ argument์ ์ฒซ ๋ฒ์งธ(0) ์์๋ฅผ ๋ฐ์ธ๋ฉํ ์๋ฆฌ์ด๋ค.
- MessageSource์
step 2. messageSource bean ๊ฐ์ฒด ์์ฑ
๊ธฐ์ ์ mvc ๊ฐ์ฒด๋ฅผ ์์ฑํ xmlํ์ผ์ ์๋์ ๋ด์ฉ์ ์ถ๊ฐํ๋ค.
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>message.label</value>
</list>
</property>
<property name="defaultEncoding" value="UTF-8" />
</bean>
- bean์ id๋ ๋ฌด์กฐ๊ฑด
messageSource๋ก ํด์ผํ๋ค. - list์ value๋ฅผ ํตํด properties์ ๊ฒฝ๋ก๋ฅผ ์ง์ ํ๋ค.
- message.label = message/label.properties
- ์ฌ๋ฌ ์ค์ ํ์ผ์ ๋ฑ๋กํ ๊ฒฝ์ฐ
<value>ํ๊ทธ๋ฅผ ์ถ๊ฐํ๋ฉด ๋๋ค.
step 3. ์ ์ฉํ๊ธฐ
<!-- ์๋จ์ ์ถ๊ฐ -->
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
...
<spring:message code="register.done" arguments="${formData.name }" />
- MessageSource๋ฅผ ์ฌ์ฉํ ๋ถ๋ถ์
<spring:message>ํ๊ทธ๋ฅผ ์ฌ์ฉํ๋ค. - code : MessageSource์ ์ ๋ ฅํ key๋ฅผ ์ ๋ ฅํ๋ค.
- arguments : messageSource์ ์ ๋ฌํ arguments๋ฅผ ์
๋ ฅํ๋ค.
- ํ๋๋ง ์
๋ ฅํ ๊ฒฝ์ฐ ->
arguments="hi" - ์ฌ๋ฌ๊ฐ ์
๋ ฅํ ๊ฒฝ์ฐ ->
arguments="hi, bye, seeyou"
- ํ๋๋ง ์
๋ ฅํ ๊ฒฝ์ฐ ->
