新建國際化所需properties文件
在resource文件夾下新建Resource Bundle咸产。
properties文件相關目錄結(jié)構(gòu)如圖:
messages.properties
NotEmpty=不能為空
messages_zh_CN.properties
NotEmpty=不能為空
messages_en_US.properties
NotEmpty=not empty
yml配置
spring:
messages:
encoding: UTF-8
basename: i18n/messages
cache-second: 3600
國際化轉(zhuǎn)換類
package com.example.i18n.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.support.RequestContextUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
/**
* @author liujy
* @description 國際化異常信息轉(zhuǎn)換工具
* @since 2020-12-25 10:13
*/
@Component
public class I18nUtil {
private static final String I18N_LANG_PARAM = "lang";
private static final String PATH_PARAMETER_SPLIT = "_";
@Autowired
private HttpServletRequest request;
@Autowired
private MessageSource messageSource;
public String getI18nMsg(String messageKey) {
Locale locale;
String lang = request.getParameter(I18N_LANG_PARAM);
if (StringUtils.hasText(lang) && lang.contains(PATH_PARAMETER_SPLIT)) {
String[] split = lang.split(PATH_PARAMETER_SPLIT);
if (split != null && split.length > 1) {
// 可查看locale源碼
locale = new Locale(split[0], split[1]);
} else {
locale = RequestContextUtils.getLocale(request);
}
} else {
locale = RequestContextUtils.getLocale(request);
}
return messageSource.getMessage(messageKey, null, locale);
}
}
Locale源碼中可查:
/** Useful constant for country.
*/
static public final Locale US = createConstant("en", "US");
/** Useful constant for language.
*/
static public final Locale SIMPLIFIED_CHINESE = createConstant("zh", "CN");
測試controller
package com.example.i18n.controller;
import com.example.i18n.utils.I18nUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author liujy
* @description
* @since 2020-12-25 11:49
*/
@RestController
@RequestMapping("/i18n")
public class I18nTestController {
@Autowired
private I18nUtil i18nUtil;
@GetMapping("/test")
public String getMsg(@RequestParam(value = "msgKey") String msgKey) {
String i18nMsg = i18nUtil.getI18nMsg(msgKey);
return i18nMsg;
}
}
啟動項目并訪問測試