
2.9 读取资源文件
在实际的项目开发中,资源文件不可或缺,因为所有的提示文字信息都要在资源文件中进行定义,而且资源文件是实现国际化技术的主要手段。如果想在SpringBoot里面进行资源文件的配置,只需要做一些简单的application.yml配置即可,而且所有注入的资源文件都可以像最初的Spring处理那样,直接使用MessageSource进行读取。
1.【mldnboot-base项目】在src/main/resources源文件夹下创建一个i18n的子目录(包)。
2.【mldnboot-base项目】建立src/main/resources/i18n/Messages.properties文件,文件内容定义如下:

3.【mldnboot-base项目】修改application.yml配置文件,追加资源文件配置,项目结构如图2-11所示。


图2-11 资源文件配置
4.【mldnboot-base项目】在MessageController控制器中注入org.springframework.context.MessageSource接口对象,并且利用此对象实现资源文件读取。

当程序中配置了资源文件之后,就可以通过MessageSource接口中提供的getMessage()方法进行资源的读取。本程序的运行效果如图2-12所示。

图2-12 读取资源文件
提示:可以借用此机制实现国际化开发。
当程序可以实现资源文件读取的时候,就意味着可以实现国际化开发处理了。可以发现,MessageSource接口中的getMessage()方法里面需要接收一个Locale类的对象,此时就可以通过Locale类的设置来获取不同的资源文件。当然,也需要在项目中配置好不同语言的资源文件。例如,本程序在src/main/resources/i18n目录中又创建了Messages_zh_CN.properties和Messages_en_US.properties(注意baseName的名称相同),如图2-13所示。

图2-13 国际化配置
这样,当读取时可以采用不同的Locale对象实现指定语言的资源读取。例如,使用如下代码就可以实现Messages_en_US.properties资源文件的读取:

需要提醒读者的是,即使提供了不同语言的资源文件,在SpringBoot中也依然需要提供Messages.properties配置文件,否则将无法实现资源文件的读取。