java配置文件
- 配置拦截器及语言环境解析
@Configuration public class WebConfig implements WebMvcConfigurer { @Bean public LocaleResolver localeResolver() { //设置cookie模式处理国际化 CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); cookieLocaleResolver.setDefaultLocale(Locale.CHINESE); return cookieLocaleResolver; } @Override public void addInterceptors(InterceptorRegistry registry) { //指定国际化标识 LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("lang"); registry.addInterceptor(localeChangeInterceptor); } }
- 配置国际化数据源
// 1.需指定名称替换默认bean @Component("messageSource") public class DBMessageSource extends AbstractMessageSource { // 自定义service @Autowired private LanguageRepository languageRepository; // 2.国际化处理方法依据key在数据库中查找对应国际化内容 @Override protected MessageFormat resolveCode(String key, Locale locale) { LanguageEntity message = languageRepository.findByKeyAndLocale(key,locale.getLanguage()); if (message == null) { message = languageRepository.findByKeyAndLocale(key,Locale.getDefault().getLanguage()); } return new MessageFormat(message.getContent(), locale); } //3.新增方法,用于后端传参国际化 public final String getMessage(String code, @Nullable Object[] args) throws NoSuchMessageException { Locale locale = LocaleContextHolder.getLocale(); String msg = getMessageInternal(code, args, locale); if (msg != null) { return msg; } String fallback = getDefaultMessage(code); if (fallback != null) { return fallback; } throw new NoSuchMessageException(code, locale); } }
其中3为自己新增的方法用于java代码中获取国际化,使用时在java代码中注入messageSource。
页面
<h2 th:text="#{home.welcome('xxx')}"></h2> <p th:text="#{home.info}"></p> <p th:text="#{home.changelanguage}"></p> <ul> <li><a href="?lang=en" th:text="#{home.lang.en}"></a></li> <li><a href="?lang=de" th:text="#{home.lang.de}"></a></li> <li><a href="?lang=zh" th:text="#{home.lang.zh}"></a></li> </ul>
参数传递为#{key(参数……)}
问题:
1.Thymeleaf中[[]]为转义符导致在js代码中使用国际化并不方便
完整代码
https://gitee.com/MeiJM/springboot-i18n
参考资料
https://github.com/PhraseApp-Blog/spring-boot-db-messageresource
https://medium.com/techcret/database-aware-i18n-messages-springboot-5715063094ef