国际化方案&枚举类中文国际化处理
枚举类中文国际化处理-改造步骤
spring 配置文件(例:applicationContext.xml)中定义 applicationContextHolder bean(务必确保优先扫描加载此bean)
- 实现I18nEnumTools
@Component
@DependsOn("I18nApplicationContextHolder")
public class I18nEnumTools {
public 18nEnumTools() {
ApplicationContext applicationContext = ApplicationContextHolder.getApplicationContext();
System.out.println("I18nApplicationContextHolder = " + applicationContext.toString());
}
public static String getMessage(String I18nKey, String defaultMessage){
String message = ApplicationContextHolder.getApplicationContext()
.getMessage(I18nKey, null,
defaultMessage, LocaleContextHolder.getLocale());
return message;
}
}
改造现有枚举类,针对中文字段xxx添加对应的xxxI18nKey字段
添加或修改中文字段xxx的getter方法
public enum DemoEnum {
/* 1.现有枚举值添加对应中文字段的I18nKey */
DEMO_1("姓名1", "测试1", "java.DemoEnum.DEMO_1.xing_ming_1", "java.DemoEnum.DEMO_1.ce_shi_1"),
DEMO_2("姓名2", "测试2", "java.DemoEnum.DEMO_2.xing_ming_2", "java.DemoEnum.DEMO_2.ce_shi_2");
private final String name;
private final String desc;
/* 2.定义字段 */
private final String nameI18nKey;
private final String descI18nKey;
DemoEnum(String name, String desc, String nameI18nKey, String descI18nKey) {
this.name = name;
this.desc = desc;
/* 3. 构造函数添加对应中文字段的I18nKey */
this.nameBdpI18nKey = nameI18nKey;
this.descBdpI18nKey = descI18nKey;
}
/* 4.使用I18nEnumTools静态方法实现动态获取i18n值 */
public String getDesc() {
return I18nEnumTools.getMessage(this.descI18nKey, this.desc);
}
public String getName() {
return I18nEnumTools.getMessage(this.nameI18nKey, this.name);
}
}
枚举引用处改为对应getter
@RequestMapping("/demo")
@ResponseBody
public Object i18nDemo(){
HashMap<String, String> result = new HashMap<>();
result.put("demo1.name", DemoEnum.DEMO_1.getName());
result.put("demo1.desc", DemoEnum.DEMO_1.getDesc());
result.put("demo2.name", DemoEnum.DEMO_2.getName());
result.put("demo2.desc", DemoEnum.DEMO_2.getDesc());
return result;
}