常常在需求中遇到国际化的要求,而国际化最常见的就是中英文切换,除了前端,后端也需要进行国际化处理,这里来记录一下我实现国际化的步骤代码。
1、在resource下的i18n下建立messages.properties、messages_en.properties、messages_zh.properties
分别配置测试变量,下面是我的配置
messages.properties
#Default Tips
#Base General Message
base.response.success.msg=成功
base.response.fail.msg=失败
messages_en.properties
#English Tips
#Base General Message
base.response.success.msg=success
base.response.fail.msg=fail
messages_zh.properties
#Chinese Tips
#Base General Message
base.response.success.msg=成功
base.response.fail.msg=失败
2、国家化配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import java.nio.charset.StandardCharsets;
/**
* @FileNName: LanguageConfig
* @Description: 国际化语言配置文件
* @Author: guoxingliang
* @Create: 2019-07-31 14:57
* @Copyright: (c)2018年 *****公司
*/
@Configuration
public class LanguageConfig {
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
messageSource.setBasenames("i18n/messages");
return messageSource;
}
}
3、获取message的工具类
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import java.util.Locale;
/**
* @FileNName: LanguageUtil
* @Description: 语言工具类获取语言信息
* @Author: guoxingliang
* @Create: 2019-07-31 15:01
* @Copyright: (c)2018年 ****公司
*/
@Component
public class LanguageUtil {
private static MessageSource messageSource;
public LanguageUtil(MessageSource messageSource) {
this.messageSource = messageSource;
}
/**
* Description: [获取单个国际化翻译值]
* Created on: 10:22 2019/8/6
* @author: guoxingliang
* @param: [msgKey]
* @return: java.lang.String
*/
public static String get(String msgKey) {
try {
return messageSource.getMessage(msgKey, null, new Locale(LocaleContextHolder.getLocale().getLanguage()));
} catch (Exception e) {
return msgKey;
}
}
}
4、提示信息key常量类
/**
* @FileNName: ConstantsUtils
* @Description: 常量类
* @Author: guoxingliang
* @Create: 2019-07-31 15:01
* @Copyright: (c)2018年 ****公司
*/
public class ConstantsUtils {
/** 提示信息message的key */
public static final String SUCCESS_MSG = "base.response.success.msg";
public static final String FAIL_MSG = "base.response.fail.msg";
}
5、测试
LanguageUtil.get(ConstantsUtils.SUCCESS_MSG);
postMan测试时需要注意Accept语言标识: