Spring boot国际化
国际化主要是引入了MessageSource,我们简单看下如何使用,以及其原理。
1.1 设置资源文件
在 properties新建i18n目录
新建message文件:
messages.properties
error.title=Your request cannot be processed
messages_zh_CN.properties
error.title=您的请求无法处理
1.2 配置
修改properties文件的目录:在application.yml或者application.properties中配置 spring.message.basename
spring:
application:
name: test-worklog
messages:
basename: i18n/messages
encoding: UTF-8
1.3 使用
引用自动注解的MessageSource,调用messageSource.getMessage
即可,注意,需要通过 LocaleContextHolder.getLocale()
获取当前的地区。
@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;
}
如何设置个性化的地区呢? forLanguageTag
即可
Locale locale = Locale.forLanguageTag(user.getLangKey());
1.4 原理分析
MessageSourceAutoConfiguration
中,实现了autoconfig
@Configuration
@ConditionalOnMissingBean(value = MessageSource.class, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {
该类一方面读取配置文件,一方面创建了MessageSource的实例:
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(this.basename)) {
messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
StringUtils.trimAllWhitespace(this.basename)));
}
if (this.encoding != null) {
messageSource.setDefaultEncoding(this.encoding.name());
}
messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
messageSource.setCacheSeconds(this.cacheSeconds);
messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
return messageSource;
}
因此,默认是加载的ResourceBundleMessageSource
,该类派生与于AbstractResourceBasedMessageSource
@Override
public final String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
String msg = getMessageInternal(code, args, locale);
if (msg != null) {
return msg;
}
if (defaultMessage == null) {
String fallback = getDefaultMessage(code);
if (fallback != null) {
return fallback;
}
}
return renderDefaultMessage(defaultMessage, args, locale);
}
最终是调用resolveCode来获取message,通过ResourceBundle来获取message
@Override
protected MessageFormat resolveCode(String code, Locale locale) {
// 遍历语言文件路径
Set<String> basenames = getBasenameSet();
for (String basename : basenames) {
ResourceBundle bundle = getResourceBundle(basename, locale);
if (bundle != null) {
MessageFormat messageFormat = getMessageFormat(bundle, code, locale);
if (messageFormat != null) {
return messageFormat;
}
}
}
return null;
}
// 获取ResourceBundle
protected ResourceBundle getResourceBundle(String basename, Locale locale) {
if (getCacheMillis() >= 0) {
// Fresh ResourceBundle.getBundle call in order to let ResourceBundle
// do its native caching, at the expense of more extensive lookup steps.
return doGetBundle(basename, locale);
}
else {
// Cache forever: prefer locale cache over repeated getBundle calls.
synchronized (this.cachedResourceBundles) {
Map<Locale, ResourceBundle> localeMap = this.cachedResourceBundles.get(basename);
if (localeMap != null) {
ResourceBundle bundle = localeMap.get(locale);
if (bundle != null) {
return bundle;
}
}
try {
ResourceBundle bundle = doGetBundle(basename, locale);
if (localeMap == null) {
localeMap = new HashMap<Locale, ResourceBundle>();
this.cachedResourceBundles.put(basename, localeMap);
}
localeMap.put(locale, bundle);
return bundle;
}
catch (MissingResourceException ex) {
if (logger.isWarnEnabled()) {
logger.warn("ResourceBundle [" + basename + "] not found for MessageSource: " + ex.getMessage());
}
// Assume bundle not found
// -> do NOT throw the exception to allow for checking parent message source.
return null;
}
}
}
}
// ResourceBundle
protected ResourceBundle doGetBundle(String basename, Locale locale) throws MissingResourceException {
return ResourceBundle.getBundle(basename, locale, getBundleClassLoader(), new MessageSourceControl());
}
最后来看getMessageFormat:
/**
* Return a MessageFormat for the given bundle and code,
* fetching already generated MessageFormats from the cache.
* @param bundle the ResourceBundle to work on
* @param code the message code to retrieve
* @param locale the Locale to use to build the MessageFormat
* @return the resulting MessageFormat, or {@code null} if no message
* defined for the given code
* @throws MissingResourceException if thrown by the ResourceBundle
*/
protected MessageFormat getMessageFormat(ResourceBundle bundle, String code, Locale locale)
throws MissingResourceException {
synchronized (this.cachedBundleMessageFormats) {
// 从缓存读取
Map<String, Map<Locale, MessageFormat>> codeMap = this.cachedBundleMessageFormats.get(bundle);
Map<Locale, MessageFormat> localeMap = null;
if (codeMap != null) {
localeMap = codeMap.get(code);
if (localeMap != null) {
MessageFormat result = localeMap.get(locale);
if (result != null) {
return result;
}
}
}
// 缓存miss,从bundle读取
String msg = getStringOrNull(bundle, code);
if (msg != null) {
if (codeMap == null) {
codeMap = new HashMap<String, Map<Locale, MessageFormat>>();
this.cachedBundleMessageFormats.put(bundle, codeMap);
}
if (localeMap == null) {
localeMap = new HashMap<Locale, MessageFormat>();
codeMap.put(code, localeMap);
}
MessageFormat result = createMessageFormat(msg, locale);
localeMap.put(locale, result);
return result;
}
return null;
}
}
作者:Jadepeng
出处:jqpeng的技术记事本--http://www.cnblogs.com/xiaoqi
您的支持是对博主最大的鼓励,感谢您的认真阅读。
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
Spring boot国际化的更多相关文章
- 玩转spring boot——国际化
前言 在项目开发中,可能遇到国际化的问题,而支持国际化却是一件很头疼的事.但spring boot给出了一个非常理想和方便的方案. 一.准备工作 pom.xml: <?xml version=& ...
- Spring boot 国际化自动加载资源文件问题
Spring boot 国际化自动加载资源文件问题 最近在做基于Spring boot配置的项目.中间遇到一个国际化资源加载的问题,正常来说只要在application.properties文件中定义 ...
- Spring Boot国际化开发实战
本章将讲解如何在Spring Boot和Thymeleaf中做页面模板国际化的支持,根据系统语言环境或者session中的语言来自动读取不同环境中的文字. 国际化自动配置 Spring Boot中已经 ...
- 58. Spring Boot国际化(i18n)【从零开始学Spring Boot】
国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式.它要求从产品中抽离所有地域语言,国家/地区和文化相关的元素.换言之,应用程序的功能和代码设计考虑在不 ...
- Spring Boot国际化支持
本章将讲解如何在Spring Boot和Thymeleaf中做页面模板国际化的支持,根据系统语言环境或者session中的语言来自动读取不同环境中的文字. 国际化自动配置 Spring Boot中已经 ...
- Spring Boot 国际化及点击链接跳转国家语言
一.国际化 在SpringBoot中已经自动帮我们配置管理国际化资源的组件,所以我们只需要编写代码就可. @Bean @ConfigurationProperties(prefix = "s ...
- spring boot 国际化MessageSource
转自:https://blog.csdn.net/flowingflying/article/details/76358970 spring中ResourceBundleMessageSource的配 ...
- spring boot 与 thymeleaf (1): 国际化
在thymeleaf 里面有个消息表达式: #{...} , 可以借此来实现国际化. 在我使用这个功能的时候, 碰到了一个问题, 按照 JavaEE开发的颠覆者 Spring Boot实战 上面编码 ...
- Spring Boot Security 国际化 多语言 i18n 趟过巨坑
网上很多的spring boot国际化的文章都是正常情况下的使用方法 如果你像我一样用了Spring Security 那么在多语言的时候可能就会遇到一个深渊 Spring Security里面的异常 ...
随机推荐
- <转载>ford-fulkerson算法2
原文链接https://www.cnblogs.com/luweiseu/archive/2012/07/14/2591573.html 作者:wlu 7. 网络流算法--Ford-Fulkerson ...
- 如何在同一台电脑上使用两个github账户(亲测有效)
1 前言 由于有两个github账号,要在同一台电脑上同步代码,需要给每一个账号添加一个SSH public key,此时推送时git push origin,不知道是哪个账号的远程仓库名称,所以需要 ...
- [C]字符串行为
未事先分配长度的字符串变量声明,占用内存空间是这个字符串长度 + 1,1用于保存\0结束标识 #include <stdio.h> #include <stdlib.h> #i ...
- 使用Gitblit 在Windows上部署Git Server
Windows平台下Git服务器搭建 首先要下载Java JDK,安装完成后设置环境变量,先把java环境配好,接下来才是下面的gitblit.关于java环境配置请看上一篇文章 gitblit下载 ...
- 19)django-cookie使用
Cookie,有时也用其复数形式 Cookies,指某些网站为了辨别用户身份.进行 session 跟踪而储存在用户本地终端上的数据(通常经过加密) 一:cookie cookie在客户端浏览器的是以 ...
- Android应用开发中三种常见的图片压缩方法
Android应用开发中三种常见的图片压缩方法,分别是:质量压缩法.比例压缩法(根据路径获取图片并压缩)和比例压缩法(根据Bitmap图片压缩). 一.质量压缩法 private Bitmap com ...
- iOS -- Effective Objective-C 阅读笔记 (1)
1: 在类的头文件中尽量 少 的引用其他头文件,尽量用 @class xxxxxx; 理解: 当你创建了一个 A 类,这个类又 需要具有 B 类的实例, 你可以直接为 A 类添加 B 类类型的 属性, ...
- STM32L476应用开发之七:流量的PID控制
在气体分析仪使用过程中,为了力求分析结果的准确性,一般要求通过的气体流量尽可能的稳定.为了保证流量控制的稳定,我们采用PID调节来控制气路阀门的开度. 1.硬件设计 我们采用的流量计为气体质量流量计, ...
- oracle数据库内存调整之增加内存
注:本文来源:小颜Kevin <oracle数据库内存调整之增加内存> 模拟操作系统内存从2G增加为8G后,调整数据库内存参数,示例中参数不作为实际生产环境参考,因为因需所取,调整参数 ...
- PhpStorm 2018 安装及破解方法
参考教程: https://blog.csdn.net/u012278016/article/details/81772566