避坑
IntelliJ IDEA 中默认的properties文件是GBK编码。修改properties的默认编码,统一为UTF-8
File -> Settings -> File Encodings -> Default encoding for properties file -> UTF-8
1、上依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、添加国际化文件
2.1 application.yml 配置
spring:
messages:
basename: static/i18n/messages #相对路径 开头请勿添加斜杠
2.2 添加国际化文件
然后在 classpath:/static/i18n
目录中添加如下国际化文件:
默认文件:messages.properties
#这里填写默认翻译,内容可以留空,但文件必须存在。
美式英语:messages_en_US.properties
#这里填写英语翻译。
user.title=User Login
中文简体:messages_zh_CN.properties
#这里填写中文翻译
user.title=用户登陆
中文繁体:messages_zh_TW.properties
#这里填写繁体翻译
user.title=用戶登陸
3、上配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import java.util.Locale;
@Configuration
public class I18NConfig {
/**
* 默认解析器:LocaleResolver 用于设置当前会话的默认的国际化语言。
*/
@Bean
public LocaleResolver localeResolver(){
SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
//默认的本地语言
sessionLocaleResolver.setDefaultLocale(Locale.CHINA);
return sessionLocaleResolver;
}
/**
* 默认拦截器 其中lang表示切换语言的参数名
* 根据自己项目情况使用,适用于前端中英文切换
*/
@Bean
public WebMvcConfigurer localeInterceptor() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
localeInterceptor.setParamName("lang");
registry.addInterceptor(localeInterceptor);
}
};
}
}
4、工具类
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
@Component
public class I18NUtils {
private static MessageSource messageSource;
public I18NUtils(MessageSource messageSource){
I18NUtils.messageSource = messageSource;
}
public static String get(String key) {
try {
return I18NUtils.messageSource.getMessage(key,null, LocaleContextHolder.getLocale());
}
catch(NoSuchMessageException e) {
return key;
}
}
}
4、使用
I18NUtils.get("user.title");