引言: 本文将介绍如何在spring boot支持i18n的最简单设置。
1 环境介绍
JDK 8, Spring Boot 1.5.6.Release, IDE: STS
2 MessageSource的基本设置
名称: spring.messages.always-use-message-format
值类型: boolean, 默认值:false
描述信息: Set whether to always apply the MessageFormat rules, parsing even messages without arguments.
MessageFormat定义了如何展示信息的格式
baseName:
名称: spring.messages.basename=messages
值类型: 位置类型的字符串
描述: Comma-separated list of basenames, each following the ResourceBundle convention; 定义了属性文件所在路径
cache-seconds:
名称:spring.messages.cache-seconds
值类型:数字类型
描述: 重新加载资源文件的时间频度;Loaded resource bundle files cache expiration, in seconds. When set to -1, bundles are cached forever.
encoding:
名称: spring.messages.encoding
值类型: 格式编码,例如:UTF-8
描述: 定义资源文件内容的编码格式, Message bundles encoding.
fallback-to-system-local:
名称: spring.messages.fallback-to-system-locale
值类型: boolean, 缺省值:true
描述: 当在获取message之时,如果没有特定的locale,则默认使用当下系统的设置;Set whether to fall back to the system Locale if no files for a specific Locale have been found.
这些配置都是在application.properites的文件中。
这里给出一个示例:
spring.messages.basename=classpath:i18n/messages
spring.messages.cache-seconds=3600
spring.messages.encoding=UTF-8
注意: 这里的18n/messages需要添加classpath进行路径的配置,否则,依然会报出资源信息无法找到的错误信息。
3 Spring Boot中支持i18n
3.1 application.properties中设置
spring.messages.basename=classpath:i18n/messages
spring.messages.cache-seconds=3600
spring.messages.encoding=UTF-8
注意basename的使用设置,在项目中i18n是其中的文件夹名称,messages只是默认的文件前缀,而非文件夹的名称。
具体的路径截图如下:
3.2 定义资源文件
根据上述的截图定义的路径i18n,我们这里定义了支持中文和英文两种Locale的资源文件,在其中,我们定义了一个message: login.failure.msg。
如果其信息是中文的话,则默认会被转码成项目制定的编码格式:
login.failure.msg=\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002
这里的中文意思是: 登录失败,请稍后重试。
在资源文件中也支持,动态的参数信息,比如:
welcome.message=welcome.msg={0},\u6B22\u8FCE\u767B\u5F55\u7CFB\u7EDF\uFF0C{1}
{0}, {1}: 即允许用户通过参数传入message之内的变量。
4 使用Message展示信息
4.1 引入MessageSource
@Autowired
private MessageSource messageSource;
通过Spring提供的annotation方式引入messageSource对象。
4.2 获取message
public Map<String, String> testCode(HttpServletRequest request) {
Locale locale = RequestContextUtils.getLocale(request);
log.info("Locale:" + locale.getLanguage());
String msg1 = this.messageSource.getMessage("login.failure.msg", null, Locale.CHINA);
log.info("Msg:" + msg1);
String[] params = {"Jack Zhang", "今天是星期一"};
String msg2 = this.messageSource.getMessage("welcome.msg", params, locale);
Map<String, String> infos = new HashMap<String,String>();
infos.put("msg1", msg1);
infos.put("msg2", msg2);
return infos;
}
在这段代码中,我们演示了两种message的使用方法。
运行结果如下:
关于Locale是基于用户请求所在的机器的Locale,通过从Request中获取对应的Locale信息。
5 总结
在Spring中提供了一套关于i18n的解决方案,可以方便地进行展示信息的替换和更新,同时也支持针对不同的语种locale的解决方案。通过i18n的方案,我们的代码中再也不用出现类似的硬编码信息了。