MessageSource

About

Spring์€ ๋‹ค๊ตญ์–ด ์ฒ˜๋ฆฌ๋กœ i18n (Internationalization (and Localization) - i-18-letters-n)์„ ์ง€์›ํ•œ๋‹ค. "์•ˆ๋…•ํ•˜์„ธ์š”"๊ฐ€ ์˜์–ด๋กœ "Hello"์ธ ๊ฒƒ์ฒ˜๋Ÿผ, ๊ตญ๊ฐ€์— ๋”ฐ๋ผ ๋‹ค๋ฅธ ์–ธ์–ด๋กœ ๋ฉ”์‹œ์ง€๋ฅผ ๋ฐ˜ํ™˜ํ•  ์ˆ˜ ์žˆ๋‹ค.

MessageSource๋ฅผ ์ด์šฉํ•ด Spring์—์„œ ๊ณตํ†ต ๋ฉ”์‹œ์ง€๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์•Œ์•„๋ณธ๋‹ค.

Message Property ํŒŒ์ผ ์„ค์ •

.properties ๋˜๋Š” .yml ์œผ๋กœ ๊ตญ๊ฐ€๋ณ„ ๋ฉ”์‹œ์ง€๋ฅผ ์ €์žฅํ•  ์ˆ˜ ์žˆ๋‹ค. (๋‹จ, .yml์€ ๋”ฐ๋กœ dependencies๋ฅผ ์„ค์น˜ํ•ด์•ผํ•˜๋Š” ๋“ฑ ์กฐ๊ธˆ ์„ค์ •์ด ํ•„์š”ํ•œ ๋“ฏ ํ•˜๋‹ค.)

  • ๊ธฐ๋ณธ์€ .properties ํŒŒ์ผ์ด๋‹ค.

  • ํŒŒ์ผ ์ด๋ฆ„ ์–‘์‹์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. - {basename}_{์–ธ์–ด์ฝ”๋“œ}_{๊ตญ๊ฐ€์ฝ”๋“œ}.properties

    • ์‹œ์Šคํ…œ ์–ธ์–ด ์ฝ”๋“œ์— ๋”ฐ๋ผ ๋‹ค๋ฅธ ์„ค์ •ํŒŒ์ผ์ด ์‚ฌ์šฉ๋œ๋‹ค.

    • e.g., message_en_uk.properties - ์˜๊ตญ ๋ฉ”์‹œ์ง€ ์„ค์ • ํŒŒ์ผ

    • e.g., message_ko.properties - ํ•œ๊ตญ์–ด ์„ค์ • ํŒŒ์ผ

messages.properties ํŒŒ์ผ์„ resources ๊ฒฝ๋กœ ๋ฐ”๋กœ ๋ฐ‘์— ๋งŒ๋“ ๋‹ค. ํ•ด๋‹น ํŒŒ์ผ์ด ๋””ํดํŠธ์ด๋ฉฐ, ์ด๋Ÿฐ ์‹์œผ๋กœ ๋ฉ”์‹œ์ง€๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

messages.properties
exception.msg=Request cannot be processed

๋งŒ์•ฝ resources ๊ฒฝ๋กœ ๋‚ด์—์„œ ๋‹ค๋ฅธ ํด๋” (e.g., messages) ํด๋”์— ๋ฉ”์‹œ์ง€ ํŒŒ์ผ๋“ค์„ ์ €์žฅํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด application.yml์—์„œ ๋‹ค์Œ๊ณผ ๊ฐ™์ด basename์„ ๋ณ€๊ฒฝํ•ด์ค€๋‹ค.

application.yml
spring:
  messages:
    basename: messages/messages

MessageSource๋กœ ๋ฉ”์‹œ์ง€ ์‚ฌ์šฉํ•˜๊ธฐ

์„ค์ •์„ ๋งˆ์ณค๋‹ค๋ฉด ์ด์ œ ๋ฉ”์‹œ์ง€๋ฅผ ๋ถˆ๋Ÿฌ์˜ฌ ์ˆ˜ ์žˆ๋‹ค.

์—ฌ๋Ÿฌ ๋ฐฉ๋ฒ•์ด ์กด์žฌํ•œ๋‹ค. Service๋ฅผ ๋งŒ๋“ค ์ˆ˜๋„ ์žˆ๊ณ , Handler, Accessor ๋“ฑ ๋‹ค์–‘ํ•œ ๋ฐฉ๋ฒ•์„ ์ด์šฉํ•ด ๋ฉ”์‹œ์ง€๋ฅผ ๋ถˆ๋Ÿฌ์˜ฌ ์ˆ˜ ์žˆ๋‹ค. ๊ฒฐ๊ตญ ์Šคํ”„๋ง์ด๋‹ˆ ๋นˆ์„ ๋งŒ๋“ค์–ด ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ๋ฅผ ์˜์กด์„ฑ ์ฃผ์ž…ํ•˜๊ณ  getMessage() ๋“ฑ์˜ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด locale์— ๋งž๊ฒŒ ๋ฉ”์‹œ์ง€๋ฅผ ๋ถˆ๋Ÿฌ์˜ค๋ฉด ๋œ๋‹ค.

๊ฐ€์žฅ ์†์‰ฌ์›Œ๋ณด์ด๋Š” ๋‹ค์Œ ๋งํฌ ์ฐธ๊ณ .

๊ทธ๋ฆฌ๊ณ  ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋„ MessageSource๋กœ (๋™์ ์œผ๋กœ) ์„ค์ •ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค. ์–‘์‹์ด ์ข‹์•„ ๋ณด์ด๋Š” ๋‹ค์Œ ๋งํฌ ์ฐธ๊ณ .

REF

Last updated