spring boot国际化之MessageSource如何使用
Hello, I''m Tina 人气:0前言
修改properties文件的目录:在application.yml或者application.properties中配置 spring.message.basename
spring: application: name: test-worklog messages: basename: i18n/messages encoding: UTF-8
MessageSource的使用:
1. 无参数
operation.success = 操作成功。
String msg1 = this.messageSource.getMessage(" operation.success ", null, Locale.CHINA);
2. 动态参数
start.ge.end = 开始日期{0}必须小于结束日期{1}!
String [] param = {startDate, endDate}; String msg =getMessage("start.ge.end", param); @Autowired private MessageSource messageSource; /** * 国际化 * * @param result * @return */ public String getMessage(String result, Object[] params) { String message = ""; try { Locale locale = LocaleContextHolder.getLocale(); message = messageSource.getMessage(result, params, locale); } catch (Exception e) { LOGGER.error("parse message error! ", e); } return message; }
补充一个方法,适用于类中无法获取到MessageSource
/** * 国际化 * 注:通过@Autowired private MessageSource messageSource无法获取 * * @param result * @return */ public String getMessage(String result, Object[] params) { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setCacheSeconds(-1); messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name()); messageSource.setBasenames("/i18n/messages"); String message = ""; try { Locale locale = LocaleContextHolder.getLocale(); message = messageSource.getMessage(result, params, locale); } catch (Exception e) { log.error("parse message error! ", e); } return message; }
总结
加载全部内容