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里面的异常 ...
随机推荐
- C# List 作为参数传递的值变化
一.示例演示 namespace TestConsole { class Program { static void Main(string[] args) { Console.WriteLine(& ...
- mysql开启binlog日志和慢查询日志
1)首先,为什么要开启binlog日志和慢查询日志呢? binlog日志会记录下数据库的所以增删改操作,当不小心删除.清空数据,或数据库系统出错,这时候就可以使用binlog日志来还原数据库,简单来说 ...
- 关于boost中enable_shared_from_this类的原理分析
首先要说明的一个问题是:如何安全地将this指针返回给调用者.一般来说,我们不能直接将this指针返回.想象这样的情况,该函数将this指针返回到外部某个变量保存,然后这个对象自身已经析构了,但外部变 ...
- 18春季训练01-3/11 2015 ACM Amman Collegiate Programming Contest
Solved A Gym 100712A Who Is The Winner Solved B Gym 100712B Rock-Paper-Scissors Solved C Gym 100712C ...
- 008_falcon磁盘io计算方法
一.falcon磁盘IO告警计算方法 (1)线上告警示例 [falcon]环境: prod 时间: 2018-11-10 22:29 共1条 [#主机磁盘io过高(appid)]主机hostname磁 ...
- 修改JDK版本配置
我使用的maven是3.0.5版本的,在创建项目的时候,默认使用的jdk为1.5版本 在项目的pom.xml中添加如下配置可修改使用的jdk版本. <properties> <!-- ...
- .NET基础之this关键字
1.限定类似名称隐藏的成员 public Employee(string name, string alias) { // Use this to qualify the fields, name a ...
- Android/IOS 微信及浏览器(h5)中唤起本地APP,唤起浮层,然后用外部浏览器打开唤起某本地APP
1 前言 微信点击链接,点击唤起某APP,在微信点开,默认是微信浏览器,点击button唤起,则会先提示浮层,然后用外部浏览器打开即可. 作为记录使用. 2 代码 相关源码如下: html: < ...
- python-面向对象之继承
一.继承介绍 继承是一种新建类的方式,新建的类称之为子类或者派生类,被继承的类称为父类/基类/超类 python中继承的特点: 1.子类可以遗传/重用父类的属性 2.子类可以有多个父类 3.Pytho ...
- HTML阻止冒泡事件的发生
阻止事件冒泡函数(低级标签的点击事件触发后,上级标签的点击事件再触发,此函数就是防止冒泡事件发生) function stopEventBubble(event){ var e=event || wi ...