java 实现自定义注解实现字典翻译 您所在的位置:网站首页 java字典类 java 实现自定义注解实现字典翻译

java 实现自定义注解实现字典翻译

#java 实现自定义注解实现字典翻译| 来源: 网络整理| 查看: 265

1、定义接口

/** * 数据字典注解 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Dict {

/** * 字典类型 * * @return */ String dictCode(); /** * 返回属性名 * * @return */ String dictText() default ""; }

2、定义切面 /** * 数据字典切面 */ @Aspect @Component @Slf4j public class DictAspect {

/** * 字典后缀 */ private static String DICT_TEXT_SUFFIX = "Text"; @Autowired private ISysDictTypeService dictTypeService; /** * 切点,切入 controller 包下面的所有方法 */ @Pointcut("execution( * com.ruoyi.*.controller.huandian.*.*(..)) || execution( * com.ruoyi.*.controller.*.*(..)) ") public void dict() { } @Around("dict()") public Object doAround(ProceedingJoinPoint pjp) throws Throwable { long time1 = System.currentTimeMillis(); Object result = pjp.proceed(); long time2 = System.currentTimeMillis(); // log.debug("获取JSON数据 耗时:" + (time2 - time1) + "ms"); long start = System.currentTimeMillis(); this.parseDictText(result); long end = System.currentTimeMillis(); // log.debug("解析注入JSON数据 耗时" + (end - start) + "ms"); return result; } private void parseDictText(Object result) { List items = new ArrayList(); if (result instanceof AjaxResult) { AjaxResult rr = (AjaxResult) result; if (rr.getData() instanceof String) { //字符串直接返回 rr.setData(rr.getData()); } else { rr.setData(getDataModel(rr.getData())); } } else if (result instanceof TableDataInfo) { TableDataInfo rr = (TableDataInfo) result; List list = (List) rr.getRows(); getData(items, list); rr.setRows(items); } else if (result instanceof PageDataInfo) { PageDataInfo rr = (PageDataInfo) result; List list = (List) rr.getData(); getData(items, list); rr.setData(items); } } private void getData(List items, List listData) { List list = listData; for (Object record : list) { ObjectMapper mapper = new ObjectMapper(); String json = "{}"; try { json = mapper.writeValueAsString(record); } catch (JsonProcessingException e) { log.error("Json解析失败:" + e); } JSONObject item = JSONObject.parseObject(json); for (Field field : ObjConvertUtils.getAllFields(record)) { if (field.getAnnotation(Dict.class) != null) { // 拿到注解的dictDataSource属性的值 String dictType = field.getAnnotation(Dict.class).dictCode(); // 拿到注解的dictText属性的值 String text = field.getAnnotation(Dict.class).dictText(); //获取当前带翻译的值 String key = String.valueOf(item.get(field.getName())); //翻译字典值对应的text值 String textValue = translateDictValue(dictType, key); //如果给了文本名 if (!StringUtils.isBlank(text)) { item.put(text, textValue); } else { // 走默认策略 item.put(field.getName() + DICT_TEXT_SUFFIX, textValue); } } // date类型默认转换string格式化日期 if ("java.util.Date".equals(field.getType().getName()) && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) { SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName())))); } } items.add(item); } } private JSONObject getDataModel(Object data) { ObjectMapper mapper = new ObjectMapper(); String json = "{}"; try { json = mapper.writeValueAsString(data); } catch (JsonProcessingException e) { log.error("Json解析失败:" + e); } JSONObject item = JSONObject.parseObject(json); for (Field field : ObjConvertUtils.getAllFields(data)) { if (field.getAnnotation(Dict.class) != null) { String dictType = field.getAnnotation(Dict.class).dictCode(); String text = field.getAnnotation(Dict.class).dictText(); String key = String.valueOf(item.get(field.getName())); String textValue = translateDictValue(dictType, key); if (!StringUtils.isBlank(text)) { item.put(text, textValue); } else { // 走默认策略 item.put(field.getName() + DICT_TEXT_SUFFIX, textValue); } } if ("java.util.Date".equals(field.getType().getName()) && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) { SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName())))); } } return item; } /** * 翻译字典文本 * * @param dictType * @param key * @return */ private String translateDictValue(String dictType, String key) { if (StringUtils.isEmpty(key)) { return null; } StringBuffer textValue = new StringBuffer(); String[] keys = key.split(","); for (String k : keys) { if (k.trim().length() == 0) { continue; } String dict_label = ""; List data = dictTypeService.selectDictDataByType(dictType); if (null == data) { return dict_label; } for (SysDictData sysDictData : data) { if (sysDictData.getDictValue().equals(key)) { dict_label = sysDictData.getDictLabel(); } } textValue.append(dict_label); //log.info("数据字典翻译: 字典类型:{},当前翻译值:{},翻译结果:{}", dictType, k.trim(), dict_label); } return textValue.toString(); } } 3、工具类 /** * 对象转换工具类 */ @SuppressWarnings("ALL") public class ObjConvertUtils { /** * 获取类的所有属性,包括父类 * * @param object * @return */ public static Field[] getAllFields(Object object) { Class clazz = object.getClass(); List fieldList = new ArrayList(); while (clazz != null) { fieldList.addAll(new ArrayList(Arrays.asList(clazz.getDeclaredFields()))); clazz = clazz.getSuperclass(); } Field[] fields = new Field[fieldList.size()]; fieldList.toArray(fields); return fields; } public static boolean isEmpty(Object object) { if (object == null) { return (true); } if ("".equals(object)) { return (true); } if ("null".equals(object)) { return (true); } return (false); } }

4、返回模型 import java.io.Serializable;

/** * 操作消息提醒 * * @author Lion Li */ @Data @NoArgsConstructor @AllArgsConstructor @Accessors(chain = true) @ApiModel(“操作消息提醒”) public class AjaxResult implements Serializable {

private static final long serialVersionUID = 7364644042368216173L; /** * 状态码 */ @ApiModelProperty("状态码") private int code; /** * 返回内容 */ @ApiModelProperty("返回内容") private String msg; /** * 数据对象 */ @ApiModelProperty("数据对象") private T data; /** * 初始化一个新创建的 AjaxResult 对象 * * @param code 状态码 * @param msg 返回内容 */ public AjaxResult(int code, String msg) { this.code = code; this.msg = msg; } /** * 返回成功消息 * * @return 成功消息 */ public static AjaxResult success() { return AjaxResult.success("操作成功"); } /** * 返回成功数据 * * @return 成功消息 */ public static AjaxResult success(T data) { return AjaxResult.success("操作成功", data); } /** * 返回成功消息 * * @param msg 返回内容 * @return 成功消息 */ public static AjaxResult success(String msg) { return AjaxResult.success(msg, null); } /** * 返回成功消息 * * @param msg 返回内容 * @param data 数据对象 * @return 成功消息 */ public static AjaxResult success(String msg, T data) { return new AjaxResult(HttpStatus.HTTP_OK, msg, data); } /** * 返回错误消息 * * @return */ public static AjaxResult error() { return AjaxResult.error("操作失败"); } /** * 返回错误消息 * * @param msg 返回内容 * @return 警告消息 */ public static AjaxResult error(String msg) { return AjaxResult.error(msg, null); } /** * 返回错误消息 * * @param msg 返回内容 * @param data 数据对象 * @return 警告消息 */ public static AjaxResult error(String msg, T data) { return new AjaxResult(HttpStatus.HTTP_INTERNAL_ERROR, msg, data); } /** * 返回错误消息 * * @param code 状态码 * @param msg 返回内容 * @return 警告消息 */ public static AjaxResult error(int code, String msg) { return new AjaxResult(code, msg, null); }

}

5、使用 添加注解即可 @ApiModelProperty(value = “状态 0-使用中 1-已归还”) @Dict(dictCode = “orderStatus”) private Integer status; ```请添加图片描述 请添加图片描述



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有