Springboot i18n
-
启动时,会通过配置文件(比如
.yml)中的spring.messages自动配置org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration#messageSourceProperties
-
通过
MessageSourceProperties配置的属性实例化一个MessageSource获取国际化值的时候就是调用
MessageSource.getMessage()方法
MessageSource的实际类型为org.springframework.context.support.ResourceBundleMessageSource
-
ResourceBundleMessageSource中有一个私有的volatile变量control
该变量的类型为
ResourceBundleMessageSource的内部类org.springframework.context.support.ResourceBundleMessageSource.MessageSourceControl
在第一次调用
MessageSource.getMessage()时会通过MessageSourceControl#newBundle去加载messages.properties文件中的内容,后续数据将放在缓存当中
使用时需要注意的点
MessageSourceProperties#fallbackToSystemLocale,默认值为true

该参数的含义是,如果通过指定的locale没有找到对应的配置文件,则使用虚拟机所在系统(例如CentOS)默认的locale
比如,在没有配置该参数的情况下:
- 通过
MessageSource.getMessage()传递的locale为zh - 配置文件为
messages.properties与messages_en.properties - 系统
locale为en_US
那么国际化的值将会从messages_en.properties中去获取,因为没有_zh的配置文件,所以拿的是系统默认的locale