๊ตญ์ ํ (i18n) ๊ธฐ๋ฅ์ ์ ๊ณตํ๋ ์ธํฐํ์ด์ค.
ApplicationContext extends MessageSource
- getMessage(String code, Object[] args, String, default, Locale, loc)
- ...
์คํ๋ง ๋ถํธ๋ฅผ ์ฌ์ฉํ๋ค๋ฉด ๋ณ๋ค๋ฅธ ์ค์ ํ์์์ด messages.properties ์ฌ์ฉํ ์ ์์
- messages.properties
- messages_ko_kr.properties
- ...
@Component
public class AppRunner implements ApplicationRunner {
@Autowired
MessageSource messageSource;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println(messageSource.getClass());
System.out.println(messageSource.getMessage("greeting", new String[]{"seunghan"}, Locale.getDefault() ));
System.out.println(messageSource.getMessage("greeting", new String[]{"seunghan"}, Locale.KOREA ));
System.out.println(messageSource.getMessage("greeting", new String[]{"seunghan"}, Locale.US ));
}
}
Locale ์ ๋ํดํธ๋ก ์คฌ๋๋ฐ ์๋ , ์ด๋ผ๊ณ ๋์ค๋ ์ด์ ๋ ํ์ฌ ์์คํ ์ ์ธ์ด๊ฐ KR๋ก ๋์ด์์ด์ ๊ทธ๋ ๋ค.
์ด๋ฆ์ ์ค๋ช ์ ์๋๋ฅผ ์ฐธ์กฐํ๋ฉด ๋๋ค.
{basename}.properties |
Default Message๋ก ์์คํ ์ ์ธ์ด ๋ฐ ์ง์ญ์ ๋ง๋ Property ํ์ผ์ด ์กด์ฌํ์ง ์์ ๊ฒฝ์ฐ ์ฌ์ฉ |
{basename}_en.properties |
์์คํ ์ธ์ด ์ฝ๋๊ฐ ์์ด์ผ ๋ ์ฌ์ฉ |
{basename}_ko.properties |
์์คํ ์ธ์ด ์ฝ๋๊ฐ ํ๊ธ์ผ ๋ ์ฌ์ฉ |
{basename}_en_UK.properties |
์์คํ ์ธ์ด ์ฝ๋๊ฐ ์์ด์ผ๋ ์๊ตญ(๊ตญ๊ฐ์ฝ๋)์ ์ํ ๋ฉ์์ง |
๋ฆด๋ก๋ฉ ๊ธฐ๋ฅ์ด ์๋ ๋ฉ์์ง ์์ค ์ฌ์ฉํ๊ธฐ
@Bean
public MessageSource messageSource(){
var messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:/messages");
messageSource.setDefaultEncoding("UTF-8");
messageSource.setCacheSeconds(3);
return messageSource;
}
https://hannamedia.tistory.com/81
์๋ฐ var ๋ณ์ํ ์ฌ์ฉ๊ฐ๋ฅ
var ํ์ ๋ณ์๋ ์๋ฐ jdk10 ์ด์๋ถํฐ ์ฌ์ฉ ๊ฐ๋ฅํ๋ค.
message๋ฅผ 1์ด๋ง๋ค ํ๋ฉด์ ์ฐ๋๋ค.
@Component
public class AppRunner implements ApplicationRunner {
@Autowired
MessageSource messageSource;
@Override
public void run(ApplicationArguments args) throws Exception {
while (true){
System.out.println(messageSource.getMessage("greeting", new String[]{"seunghan"}, Locale.KOREA ));
System.out.println(messageSource.getMessage("greeting", new String[]{"seunghan"}, Locale.US ));
Thread.sleep(1000l);//1์ด ๋ง๋ค ์ฐ๋๋ค.
}
}
}
@SpringBootApplication
public class Demospring51Application {
public static void main(String[] args) {
SpringApplication.run(Demospring51Application.class, args);
}
@Bean
public MessageSource messageSource(){
var messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:/messages");//ํด๋์คํจ์ค ๊ธฐ์ค์ผ๋ก messages๋ฅผ ์ฝ๋๋ค.
messageSource.setDefaultEncoding("UTF-8");//ํ๊ธ์ด ๊นจ์ง์ง ์๋๋ก
messageSource.setCacheSeconds(3);//์บ์ฑ์๊ฐ์ ์ต๋ 3์ด๋ก ์ ํ.
return messageSource;
}
}
์ด๋ ์ค๊ฐ์ messages.properties ํ์ผ์ ์์ ํ๋ฉด ์๋์ ๊ฐ์ด ๋ฐ๋๊ฒ ๋๋ค. (๊ผญ ๋น๋๋ฅผ ํด์ค์ผํจ)