一、简介
i18n(其来源是英文单词 internationalization的首末字符i和n,18为中间的字符数)是“国际化”的简称。通常与i18n相关的还有L10n(“本地化”的简称)。
二、代码实现
2.1 properties文件
在resource资源文件夹下,新建文件夹i18n,并创建资源文件:
简体中文:default_zh_CH.properties
英文:default_en_us.properties
2.2 yml配置文件
配置application.yml配置文件中的basename国际化文件路径
2.3 Utils工具类获取国际化
@Component
public class MessageUtils {
private static MessageSource messageSource;
public MessageUtils(MessageSource messageSource){
MessageUtils.messageSource = messageSource;
}
public static String getMessage(String key){
try{
/**
* 根据消息键和参数 获取消息 委托给spring messageSource
* @param code 消息键
* @param args 参数
* @return 获取国际化翻译值
*/
//LocaleContextHolder.getLocale() 中文:Locale.SIMPLIFIED_CHINESE 英文: Locale.US
return messageSource.getMessage(key,null, LocaleContextHolder.getLocale());
}catch (Exception e){
return key;
}
}
}
三、测试
3.1 测试接口
@RestController
public class testController {
@GetMapping("/i18n")
public String i18n(){
return MessageUtils.getMessage("msg.00001");
}
}
3.2 结果
简体中文:
英文: