๋ฐ์ํ
ํ๊ฒฝ์ค์
์คํ๋ง์ ๊ธฐ๋ณธ์ ์ธ ๋ฉ์์ง ๊ด๋ฆฌ ๊ธฐ๋ฅ์ ์ ๊ณตํ๋ค.
โ ์ธํฐํ์ด์ค MessageSource ์ ๊ตฌํ์ฒด์ธ ResourceBundleMessageSource๋ฅผ ์คํ๋ง ๋น์ผ๋ก ๋ฑ๋กํ๋ฉด๋๋ค.
- ์คํ๋ง ํ๋ ์์ํฌ
- code
@SpringBootApplication์ด๋ @ComponantScan์ด ์๋ ํด๋์ค์์ ์ ์ฝ๋๋ฅผ ์ ์ผ๋ฉด ๋๋ค.@Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasenames("messages", "errors"); messageSource.setDefaultEncoding("utf-8"); return messageSource; }
- code
- ์คํ๋ง ๋ถํธ (Gradle)
- ์คํ๋ง ๋ถํธ๋ ๋ฑ๋กํ์ง ์์๋ ์๋์ผ๋ก MessageSource๋ฅผ ์คํ๋ง ๋น์ผ๋ก ์๋ ๋ฑ๋กํ๋ค.
- application.properties์ ๊ธฐ๋ณธ์ค์ ์ spring.message.basename=messages ์ด๋ ๊ฒ ๋์ด์๋ ๊ฑฐ์ ๊ฐ์๋ฐ,
spring.message.basename=messages, config.i18n.messages ์ ๊ฐ์ด ์ถ๊ฐ์์ฑํด ์ฌ์ฉํ ์ ์๋ค.
- ์คํ๋ง ๋ถํธ๋ ๋ฑ๋กํ์ง ์์๋ ์๋์ผ๋ก MessageSource๋ฅผ ์คํ๋ง ๋น์ผ๋ก ์๋ ๋ฑ๋กํ๋ค.
ํ ์คํธ์์ ์ฌ์ฉํด๋ณด๊ธฐ
- ํ์ผ์์ฑ
- resource ํด๋ ์๋์ ๋ง๋ ๋ค.
- resource ํด๋ ์๋์ ๋ง๋ ๋ค.
- ๊ฐ๋จํ๊ฒ ์ฝ๋๋ฅผ ์ ์ด๋ณธ๋ค.
- ๋ฉ์์ง ๊ฐ์ ธ์ค๊ธฐ
- MessageSource์ ๋ฑ๋กํ ์ด๋ฆ์ผ๋ก ms.getMessage("hello", null, null); ์ด๋ ๊ฒ ๊ฐ์ ธ์ฌ ์ ์๋ค.
- MessageSource์ ๋ฑ๋กํ ์ด๋ฆ์ผ๋ก ms.getMessage("hello", null, null); ์ด๋ ๊ฒ ๊ฐ์ ธ์ฌ ์ ์๋ค.
- ๊ธฐ๋ณธ ๋ฉ์์ง์ ํ๋ผ๋ฏธํฐ ์ฌ์ฉํ๊ธฐ
- ms.getMessage("no_code", null, "๊ธฐ๋ณธ ๋ฉ์์ง", null);
"no_code"๋ผ๋ ์ด๋ฆ์ ๋ฉ์์ง๊ฐ ์์ผ๋ฉด param์ด 4๊ฐ์ผ ๋ ์ธ๋ฒ์งธ์ ๊ธฐ๋ณธ ๋ฉ์์ง๋ฅผ ์ ์ ์ ์๋ค. - ms.getMessage("hello.name", new Object[]{"Spring"}, null);
new Object[]{"Spring"} ๋ผ๋ ๊ฐ์ ๋ฃ์ผ๋ฉด ๊ธฐ์กด ๋ฉ์์ง์ ํฉ์ณ์ง ๋ฉ์์ง๋ฅผ ๋ง๋ค ์ ์๋ค.
- ms.getMessage("no_code", null, "๊ธฐ๋ณธ ๋ฉ์์ง", null);
- ๊ตญ์ ํ
- ms.getMessage("hello", null, Locale.ENGLISH)
param ๋ง์ง๋ง์ Locale ์ง์ญ์ ์ง์ ํ๋ฉด ๋๋๋ฐ, ์ด ๋ ๋ง์ฝ ๋ฑ๋ก๋์ง ์์ ์ง์ญ์ด ์์ผ๋ฉด ๊ธฐ๋ณธ message ๋น์ ๊ฐ์ ธ์ ์ฌ์ฉํ๋ค.
- ms.getMessage("hello", null, Locale.ENGLISH)
ํ์๋ฆฌํ์ ์ ์ฉํ๊ธฐ
#{...}
- ์ ์ฉ ํ๋ฉด
label์ l์ ๋น ํธ๋ ธ๋ค. ์ด ์ค๋ฅ๋ก ๋ฉ์์ง๋ก ๊ต์ฒด๋ ๊ฒ์ ํ์ธ ํ ์์๋ค. - messages.properties ์ ์ฝ๋ ์ถ๊ฐ.
- thymeleaf ํ๋ฉด
- th:text="#{๋ฉ์์ง}" ์ด์ ๊ฐ์ ํํ๋ก ์ฌ์ฉํ๋ค.
- <h2 th:text="#{page.item}">
- <label for="itemId" th:text="#{label.item.id}">
- ํ๋ผ๋ฏธํฐ๋ ์ฌ์ฉ๋ฒ
- <p th:text="#{hello.name(${item.itemName})}"></p>
- <p th:text="#{hello.name(${item.itemName})}"></p>
- ๊ตญ์ ํ
- messages_en.properties๋ฅผ ์ถ๊ฐํ๋ค.
- ํฌ๋กฌ ์ค์ ์์ ์์ด๋ฅผ 1์์๋ก ์ง์ ํ๋ค.
- ์์์ ํ์๋ฆฌํ์ ๋์ผํ ์ด๋ฆ์ผ๋ก ๋ฉ์์ง๋ฅผ ์ ์ฉํ๊ธฐ ๋๋ฌธ์ ์๋์ผ๋ก ๊ตญ์ ํ ๋์ด์๋ค.
- messages_en.properties๋ฅผ ์ถ๊ฐํ๋ค.
์คํ๋ง ๊ตญ์ ํ ๋ฉ์์ง ์ ํ์์ Locale ์ ํ ๋ฐฉ์์ ๋ณ๊ฒฝํ๊ณ ์ถ์ผ๋ฉด,
LocaleResolver๋ฅผ ๊ฒ์ํด ์ ๋ณด๋ฅผ ์ฐพ์ ์ฌ์ฉํ๋ฉด๋๋ค.
โป ์ฐธ์กฐ : https://www.inflearn.com/roadmaps/373E
๋ฐ์ํ
'๐ Spring' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Spring]๋ค์ํ ์์กด๊ด๊ณ ์ฃผ์ ๋ฐฉ๋ฒ @Autowired (0) | 2025.02.26 |
---|---|
[Spring]์ปดํฌ๋ํธ ์ค์บ๊ณผ ์์กด๊ด๊ณ ์๋ ์ฃผ์ (0) | 2025.02.25 |
[Spring]@Configuration๊ณผ ๋ฐ์ดํธ์ฝ๋ ์กฐ์ (0) | 2025.02.25 |
[Spring]์์ ์๋ฐ ์ฝ๋๋ก ์๋ก์ด ํ ์ธ ์ ์ฑ ์ ์ฉ์ ๋ฌธ์ ์ (1) | 2025.01.18 |
[Spring]์์ ์๋ฐ ๊ฐ๋ฐ-์ฃผ๋ฌธ๊ณผ ํ ์ธ ๋๋ฉ์ธ. ๊ทธ๋ฆฌ๊ณ ํ ์คํธ (1) | 2025.01.17 |