1. 启动时,会通过配置文件(比如.yml)中的spring.messages自动配置

    org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration#messageSourceProperties

    image-20220430181430281

  2. 通过MessageSourceProperties配置的属性实例化一个MessageSource

    获取国际化值的时候就是调用MessageSource.getMessage()方法

    image-20220430185525952

    MessageSource的实际类型为org.springframework.context.support.ResourceBundleMessageSource

    image-20220430181717157

  3. ResourceBundleMessageSource中有一个私有的volatile变量control

    image-20220430183021396

    该变量的类型为ResourceBundleMessageSource的内部类

    org.springframework.context.support.ResourceBundleMessageSource.MessageSourceControl

    image-20220430183212379

    在第一次调用MessageSource.getMessage()时会通过MessageSourceControl#newBundle去加载messages.properties文件中的内容,后续数据将放在缓存当中

使用时需要注意的点

MessageSourceProperties#fallbackToSystemLocale,默认值为true

image-20220430193315179

该参数的含义是,如果通过指定的locale没有找到对应的配置文件,则使用虚拟机所在系统(例如CentOS)默认的locale

比如,在没有配置该参数的情况下:

  1. 通过MessageSource.getMessage()传递的localezh
  2. 配置文件为messages.propertiesmessages_en.properties
  3. 系统localeen_US

那么国际化的值将会从messages_en.properties中去获取,因为没有_zh的配置文件,所以拿的是系统默认的locale