需求:
在接口服务中,根据不同的语言标识传参,返回不同的语言提示语。

设计前提

由于这项工作是在接口设计完之后展开的,所以只能在现有的接口开发上进行完善。
接口调用的主要形式有GET以及POST下不同形式的传参,如Content-Type为application/json或application/x-www-form-urlencoded。返回参数为固定设计好的构造类。

1
2
3
4
5
6
7
public class JsonResult<T> {
private String flag;
private EErrorCode errorCode;
private String message;
private T data;
//此处省略多种参数构造函数及封装方法
}

设计思路

利用jdk本身的工具类Locale,以及spring对语言配置的初始化,构建国际化读取信息的工具类。

  • 在resources底下创建多语言配置文件,如messages.properties,本项目中默认的配置文件为中文,只需要创建英文的配置文件来做切换。

  • 在spring的配置文件中指定路径

    1
    2
    3
    spring
    messages
    basename: i18n/messages
  • 构建国际化工具类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.MessageSource;
    import org.springframework.stereotype.Component;
    import java.util.Locale;
    /**
    * 国际化工具类
    *
    * @author eazonshaw
    */
    @Component
    public class BusLocaleUtil {

    private static MessageSource messageSource;

    @Autowired
    public void init(MessageSource messageSource){
    BusLocaleUtil.messageSource = messageSource;
    }

    /**
    * 获取国际化字符串
    * @param key 对应配置文件的key
    * @param lang 语言标识,默认为中文(CH),可选英文(EN)
    * @param params 占位符参数,其中日期为Java.Util.Date类型
    * @return 国际化字符串
    */
    public static String getMessage(String key, String lang, Object[] params) {
    Locale locale;
    if(lang!=null && lang.equals("EN")) locale = Locale.US;
    else locale = Locale.CHINA;
    return messageSource.getMessage(key, params, "", locale);
    }
    }
  • 在配置文件中定义kv值
    messages.properties

    1
    ADDORDER.STORE.NOENOUGH = 您所选的{0, date, long}的{1, choice, 0#房间|1#车辆|2#翻译|3#礼仪|4#景点}门票库存不足,请重新选择!

messages_en_US.properties

1
ADDORDER.STORE.NOENOUGH = Your {1, choice, 0#hotel|1#limousine|2#translator|3#etiquette|4#tour} reservation for {0, date, long} is not available.Please reserve another time!
  • 接口调用时使用
    1
    2
    Object[] params = {new Date(),1};
    return BusLocaleUtil.getMessage("ADDORDER.STORE.NOENOUGH",lang,params);

接口返回结果 lang=”CH”:您所选的2019年5月21日的车辆门票库存不足,请重新选择!
lang=”EN”:Your limousine reservation for May 21, 2019 is not
available.Please reserve another time!

后续完善

网上提供的方法大多是在spring中配置bean,重新定义Locale的加载类,但是大多数切换都只适用于GET请求。
在设计时有想过在国际化调用时,根据request里的参数,自动切换语言环境。但由于spring中,在controller里用@RequestBody里接收的参数只能接收一次,再次接收只能接收到空值。如果需要实现再次获取request里的值,需要添加接收前的拦截处理。

重点难点

国际化配置文件的value值的占位符的灵活运用。 //TODO 待补充