参考
spring boot后端 i18n国际化
SpringBoot 国际化i18n
SpringBoot 实现国际化 [i18n]
定义国际化文件
在response文件夹下新建 i18n,我们在里面写吧,新建3个文件: 【[记住!!! properties编码要设置utf-8]
】
设置utf-8编码
安装插件Resource Bundle Editor
配置枚举
支持多个目录
此场景一般用于,封装的core包中已经有一组错误码,可以封装第二组
spring:
messages:
basename: i18n/local, i18n2/local #表示放在classpath的i18n文件夹,文件前缀为local
# basenames: i18n/local, i18n2/local
encoding: utf-8
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration源码中会通过逗号切分
查找逻辑
封装方法
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
import com.gxu.common.core.util.ServiceHelper;
import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
public class LocalUtil {
private static MessageSource MESSAGE_SOURCE;
public LocalUtil() {
}
public static String get(String code) {
return getMessage(code, (Object[])null, "");
}
public static String get(String code, Object[] args) {
return getMessage(code, args, "");
}
public static MessageSource getMessageSource() {
if (MESSAGE_SOURCE == null) {
MESSAGE_SOURCE = (MessageSource)ServiceHelper.getBean(MessageSource.class);
}
return MESSAGE_SOURCE;
}
public static void setLocal(Locale local) {
LocaleContextHolder.setLocale(local);
}
private static String getMessage(String code, Object[] args, String defaultMessage) {
Locale locale = LocaleContextHolder.getLocale();
return getMessageSource().getMessage(code, args, defaultMessage, locale);
}
}
配置web拦截器
public class I18nInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
log.info("访问");
Cookie cookie = Arrays.stream(request.getCookies()).filter(c-> "lang".equals(c.getName())).findFirst().orElse(null);
if(cookie!= null && cookie.getValue() != null){
log.info("lang:{}",cookie.getValue());
String[] values = cookie.getValue().split(SymbolConstants.UNDERSCORE);
if(values.length > 1){
Locale locale = new Locale(values[0],values[1]);
if("en".equals(values[0])){
LocalUtil.setLocal(Locale.US);
}else{
LocalUtil.setLocal(Locale.SIMPLIFIED_CHINESE);
}
}
}
return true;
}
}
@Slf4j
@Configuration
public class CustomWebMvcConfigurer implements org.springframework.web.servlet.config.annotation.WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new I18nInterceptor()).addPathPatterns("/*/**");
}
}
调用
@Operation(summary = "国际化")
@GetMapping("/lang")
Result<String> testI18n( Integer code)
{
if(code == -1){
throw new SassException(StoreExceptionEnums.ERROR,new String[]{"科技公司","张三"});
}
Locale locale =Locale.getDefault();
log.info("{} {}: {}",locale, code, LocalUtil.get(code.toString()));
return Result.ok(LocalUtil.get(code.toString()));
}
配置变量占位符
22201=企业【{0}】下的用户[{1}]不存在