(本项目是基于Dubbo的,所以会有后端服务和前端Controller两次国际化的配置)
对后端服务的异常代码进行国际化版本的配置
1.在provider的resources中新建一个properties文件夹在其中新建一个messages的文件夹,新建两个properties,内容如下:
promptMessage_me_JD.properties:
#订单处理
orderCancel = 药品订单{0}取消失败
selectUserInfo = 查询药品【{0}】异常,异常信息【{1}】
user_name = hp
promptMessage_no_JD.properties:
#订单处理
orderCancel = 订单{0}取消失败
selectUserInfo = 查询用户【{0}】异常,异常信息【{1}】
user_name = 韩枫
2.在resources的spring-mybatis.xml(就是spring的配置文件,我这叫这名字,可能不一样)配置如下:
<!-- 国际化支持 -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>properties.messages.promptMessage</value>
</list>
</property>
<!-- 支持UTF-8的中文 -->
<property name="cacheSeconds" value="0"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<!-- 实例化 -->
<bean id="messageSourceHelper" class="com.hanpeng.utils.MessageSourceHelper">
<property name="messageSource" ref ="messageSource"></property>
</bean>
什么意思呢,properties.messages.promptMessage是刚才的properties的前缀,后缀是后面用来匹配的。
3.创建MessageSourceHelper帮助类:
package com.hanfeng.utils;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ResourceBundleMessageSource;
import javax.annotation.Resource;
import java.util.Locale;
/**
* @program: XXX
* @description: 国际化信息帮助类
* @author: by hanfeng
* @create: 2019-03-18 20:17
**/
public class MessageSourceHelper {
private static MessageSource messageSource;
public static String getMessage(String code, Object[] args, String defaultMessage,Locale locale) {
String msg = messageSource.getMessage(code, args, defaultMessage, locale);
return msg != null ? msg.trim() : msg;
}
public static String getMessage(String code, Object[] args, String defaultMessage) {
String msg = messageSource.getMessage(code, args, defaultMessage, null);
return msg != null ? msg.trim() : msg;
}
public static String getMessage(String code, Object[] args, Locale locale) {
String msg = messageSource.getMessage(code, args, locale);
return msg != null ? msg.trim() : msg;
}
public static String getMessage(String code, Object[] args) {
String msg = messageSource.getMessage(code, args, null);
return msg != null ? msg.trim() : msg;
}
public void setMessageSource(ResourceBundleMessageSource messageSource) {
MessageSourceHelper.messageSource = messageSource;
}
}
用来封装MessageSource类
4.通过以上配置spring的i18n国际化就完成了
下面是一个示例:
public User getUserInfoByCondition(User user) {
try {
return userDao.selectUserInfoByCondition(user);
}catch (Exception e){
LOGGER.error(MessageFormat.format("查找用户信息失败!异常信息:{0}", e.getMessage()), e);
throw new BusinessException(MessageSourceHelper.getMessage("selectUserInfo",new Object[] {user.getUsername(),"SQL错误"},new Locale("no","JD")));
}
}
5.如何自动配置各个版本呢,大家可以看一下Locale的源码,上述代码new Locale("no","JD")中,no代表的是语言,JD代表的是地区,和上面的properties的后缀进行匹配
可能我的描述没有那么明白,大家有问题可以在下面评论,谢谢