在i18n_zh_CN.properties文件中
userName=陈皮
在i18n_en_US.properties文件中
userName=Peel
我们通过如下方式,就可以获取相应语言环境下的信息了,如下:
Locale chinaLocale = Locale.CHINA;
ResourceBundle resourceBundle = ResourceBundle.getBundle(“i18n”, chinaLocale);
String userName = resourceBundle.getString(“userName”);
System.out.println(userName);
Locale usLocale = Locale.US;
resourceBundle = ResourceBundle.getBundle(“i18n”, usLocale);
userName = resourceBundle.getString(“userName”);
System.out.println(userName);
// 输出结果
陈皮
Peel
对于不同地域语言环境的用户,我们是如何处理国际化呢?其实原理很简单,假设客户端发送一个请求到服务端,在请求头中设置了键值对,“Accept-Language”:“zh-CN”,根据这个信息,可以构建出一个代表这个区域的本地化对象Locale,根据配置文件的baseName和Locale对象就可以知道读取哪个配置文件的属性,将要显示的文字格式化处理,最终返回给客户端进行显示。
=============================================================================
在Springboot中,我们会使用到一个MessageSource接口,用于访问国际化信息,此接口定义了几个重载的方法。code即国际化资源的属性名(键);args即传递给格式化字符串中占位符的运行时参数值;local即本地化对象;resolvable封装了国际化资源属性名,参数,默认信息等。
-
String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale)
-
String getMessage(String code, @Nullable Object[] args, Locale locale)
-
String getMessage(MessageSourceResolvable resolvable, Locale locale)
Springboot提供了国际化信息自动配置类MessageSourceAutoConfiguration,它可以生成MessageSource接口的实现类ResourceBundleMessageSource,注入到Spring容器中。Message