post-custom-banner

๐Ÿ”—ย Spring Message Source ์„ค์ •

โœ๏ธย message ์‚ฌ์šฉํ•˜๊ธฐ

โš ๏ธย ํ•œ๊ธ€ ๊นจ์ง ํ˜„์ƒ ํ•ด๊ฒฐ๋ฐฉ๋ฒ•

  • MessageSource ๋ฅผ ์‚ฌ์šฉํ•ด ๋“ฑ๋กํ•œ ๋ฉ”์‹œ์ง€๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.
@SpringBootTest
public class MessageSourceTest {

    @Autowired
    MessageSource ms;

๐Ÿ“ย ๊ธฐ๋ณธ ๋ฉ”์‹œ์ง€ ์กฐํšŒ ๋ฐฉ๋ฒ•

  • ์ฒซ๋ฒˆ์งธ Param - code
    • ๋ฉ”์‹œ์ง€ ํŒŒ์ผ์— ๋“ฑ๋กํ•œ ์ฝ”๋“œ (๋ณ€์ˆ˜)
  • ๋‘๋ฒˆ์งธ Param - args
    • ํŒŒ์ผ์— ์„ค์ •ํ•œ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ args ๋กœ ์น˜ํ™˜์‹œ์ผœ์คŒ
  • ์„ธ๋ฒˆ์งธ Param - locale
    • ๋กœ์ผ€์ผ ์ •๋ณด
    • null ๋กœํ•˜๋ฉด ๊ธฐ๋ณธ๊ฐ’ (basename) ์œผ๋กœ ์„ค์ •๋œ ํŒŒ์ผ์ด ์‹คํ–‰๋จ
@Test
void helloMessage() {
    String result = ms.getMessage("hello", null, null);
    assertThat(result).isEqualTo("์•ˆ๋…•");
}

๐Ÿ“ย ๋ฉ”์‹œ์ง€๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ

  • ํŒŒ์ผ์— ์ •์˜๋˜์ง€ ์•Š์€ ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•  ๊ฒฝ์šฐ NoSuchMessageException ์ด ๋ฐœ์ƒ๋œ๋‹ค.
@Test
void notFoundMessageCode() {
    assertThatThrownBy(() -> ms.getMessage("no_code", null, null))
            .isInstanceOf(NoSuchMessageException.class);
}

๐Ÿ“ย ๋””ํดํŠธ ๋ฉ”์‹œ์ง€

  • args ์™€ locale ์‚ฌ์ด์— ๋””ํดํŠธ ๋ฉ”์‹œ์ง€๋ฅผ ์ž…๋ ฅํ•˜๋Š” ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ๋‹ค.
    • ์ •์˜๋˜์ง€ ์•Š์€ ์ฝ”๋“œ๋ฅผ ์š”์ฒญํ•  ๊ฒฝ์šฐ ๊ธฐ๋ณธ์ ์œผ๋กœ ๋‚˜ํƒ€๋‚˜๋Š” ๋ฉ”์‹œ์ง€ ์ด๋‹ค.
@Test
void defaultMessageCode() {
    String result = ms.getMessage("no_code", null, "๊ธฐ๋ณธ ๋ฉ”์‹œ์ง€", null);
    assertThat(result).isEqualTo("๊ธฐ๋ณธ ๋ฉ”์‹œ์ง€");
}

๐Ÿ“ย args ์‚ฌ์šฉ

  • args ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ํ™œ์šฉํ•ด ์ƒํ™ฉ์— ๋งž๊ฒŒ message ๋ฅผ ๋ณ€ํ˜•์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ค.
    • Object ๋ฐฐ์—ด๋กœ ๋„˜๊ฒจ์ฃผ์–ด์•ผ ํ•œ๋‹ค,
    • ๋ฐฐ์—ด์˜ ์ธ๋ฑ์Šค๋ฒˆํ˜ธ์— ๋งž๊ฒŒ ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ ๋ณ€ํ˜•๋œ๋‹ค.
      • hello.name=์•ˆ๋…• {0}
@Test
void argumentMessage() {
    String result = ms.getMessage("hello.name", new Object[]{"Spring"}, null);
    assertThat(result).isEqualTo("์•ˆ๋…• Spring");
}

โœ๏ธย ๊ตญ์ œํ™” ์‚ฌ์šฉํ•˜๊ธฐ

  • null
    • default ๊ฐ’์ธ message ๊ฐ€ ์‹คํ–‰๋œ๋‹ค.
  • Locale.KOREA
    • KOREA ๋ฅผ ์„ค์ •ํ•˜์ง€ ์•Š์•˜์œผ๋ฏ€๋กœ default ๊ฐ’์ธ message ๊ฐ€ ์‹คํ–‰๋œ๋‹ค.
  • Locale.ENGLISH
    • Spring ์ด ENGLISH ์„ en ์œผ๋กœ ๋ณ€๊ฒฝ๋˜ message_en ํŒŒ์ผ์ด ์‹คํ–‰๋œ๋‹ค.
@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");
}
profile
์ž˜๋ชป๋œ ๋‚ด์šฉ PR ํ™˜์˜
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€