使用的SpringBoot版本是2.3.5
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/>
</parent>
一、简单测试
(1)、配置文件
messages:
basename: i18n/messages
encoding: UTF-8
或者使用 Bean进行代码配置
@Configuration
public class LocalMessageConfig {
/**
* 系统国际化文件配置
* @return MessageSource
*/
@Bean(name = "messageSource")
public MessageSource messageSource() {
ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
resourceBundleMessageSource.setDefaultEncoding("UTF-8");
resourceBundleMessageSource.setBasenames("i18n/messages");
return resourceBundleMessageSource;
}
}
(2)、在resource目录下i18n文件夹,文件夹下建三个文件,文件名与配置文件中的basename中名称一致,在这里都是messages
message.properties文件内容:
login.fail = {0} 登陆失败
message_en_US.properties文件内容:
login.fail = {0} login fail
message_zh_CN.properties文件内容:
login.fail = {0} 登陆失败
(3)、测试
@RequestMapping("/hello")
@RestController
public class I18nController {
@Autowired
private MessageSource messageSource;
@GetMapping
public String msg(){
String stringMsg1 = messageSource.getMessage("login.fail",new Object[]{username},Locale.CHINA);
String stringMsg2 = messageSource.getMessage("login.fail",new Object[]{username},Locale.US);
System.out.println("stringMsg1---"+stringMsg1 +"\n" + "stringMsg2---"+stringMsg2);
//Locale locale = LocaleContextHolder.getLocale();
//String message = messageSource.getMessage("login.fail", new Object[]{username}, locale);
}
}
stringMsg1---admin 登陆失败
stringMsg2---admin login fail
二、添加一些工具类