项目示例仓库
[Coding]https://meostar.coding.net/public/message-source-usage/message-source-usage/git
代码分支说明
- master分支
无配置,虽然能用,但是强烈建议使用配置。
- code分支
通過代码配置MessageSource
,对应下面第二章节 - 3.2
- yml分支
通過yml
文件配置MessageSource
一、国际化
1. 简述
国际化是什么,简单地说就是,在不修改内部代码的情况下,根据不同语言及地区显示相应的语言界面。
2. Spring官方解释
Spring中对国际化文件支持的基础接口是MessageSource
。
参照Spring对于MessageSource
解释的官方文档:
Strategy interface for resolving messages, with support for the parameterization and internationalization of such messages.
Spring provides two out-of-the-box implementations for production:
ResourceBundleMessageSource
, built on top of the standard ResourceBundle
ReloadableResourceBundleMessageSource
, being able to reload message definitions without restarting the VM
意思为:
Spring提供了两种开箱即用的实现,一种是标准实现,一种是运行时可重新加载。
本文允许转载,转载本文时请加上本文链接:
https://blog.youkuaiyun.com/nthack5730/article/details/82870368
https://www.jianshu.com/p/a354d3f849ec
对于爬虫网站随意爬取以及转载不加原文链接的,本人保留追究法律责任的权力!
二、SpringBoot中使用MessageSource国际化
1. SpringBoot自动化配置国际化支持
Spring Boot已经对i18n国际化做了自动配置,自动配置类为:
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration
使用MessageSource
时只要@Autowired
就行:
@Autowired
private MessageSource messageSource;
而Spring在启动的时候装备的实现类是:
org.springframework.context.support.ResourceBundleMessageSource
但是很多人会说:我用了Autowired为什么调用messageSource.getMessage(...)
却返回空内容?
这是因为SpringBoot对国际化properties文件路径默认设定是在message
文件夹下,找不到文件夹,所以就没有信息返回呗。
下面会进行如何自定义i18n国际化配置讲述。
2. 常见国际化支持配置参数解释
MessageSource
国际化配置中有几个参数是常见的,在这里必须要说明下,因为知道遮几个参数才能理解下面的配置:
basename
:默认的扫描的国际化文件名为messages,即在resources建立messages_xx.properties文件,可以通过逗号指定多个,如果不指定包名默认从classpath下寻找。
encoding
:默认的编码为UTF-8,也可以改为GBK等等
cacheSeconds
:加载国际化文件的缓存时间,单位为秒,默认为永久缓存。
fallbackToSystemLocale
:当找不到当前语言的资源文件时,如果为true默认找当前系统的语言对应的资源文件如messages_zh_CN.properties,如果为false即加载系统默认的如messages.properties文件。
3. 自定义i18n国际化配置
很多时候我们要修改自动配置中的某些配置参数,例如message.properties文件所在的文件夹路径、properties文件的编码格式等等,可以用以下两种方式进行配置修改,选一个就好:
- 修改Bean,直接返回一个配置Bean
- 使用配置文件(比较推荐这种做法)
3.1 在application.yml配置文件中
在配置文件中加入下面的配置:(application.properties配置文件麻烦自行转换下)
spring:
messages:
basename: i18n/messages
encoding: UTF-8
3.2 用Bean进行代码配置
在@Configuration
的类
下面加入Bean配置就好,下面是完整的类代码:
@Configuration
public class MessageSourceConfig {
@Bean(name = "messageSource")
public ResourceBundleMessageSource getMessageSource() throws Exception {
ResourceBundleMessageSource resourceBundleMessa