字典注解:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Dict {String dictType();String dictLabel() default "";}

定义切面拦截controller接口


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.daimler.cg.common.lib.base.util.common.ResponseBean;
import com.daimler.cg.imp.client.currency.Dict;
import com.daimler.cg.imp.sysdict.service.SysDictService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;@Aspect
@Component
@Slf4j
public class DictAspect {//表对应字段加上DictLabel即可显示出文本private static String DICT_TEXT_SUFFIX = "_DictLabel";@Resourceprivate SysDictService dictService;/*** 定义切点Pointcut拦截所有对服务器的请求*/
//    @Pointcut("execution(* com.daimler..controller..*(..))")
//    public void excudeService() {
//    }/*** 这是触发DictionariesService的时候会执行的,在环绕通知中目标对象方法被调用后的结果进行再处理*  @Around("excudeService()")*/@Around("@annotation(InterceptInterface)")public Object doAround(ProceedingJoinPoint pjp) throws Throwable {log.error("{}",pjp);//这是定义开始事件long time1 = System.currentTimeMillis();//这是方法并获取返回结果Object result = pjp.proceed();//这是获取到结束时间long time2 = System.currentTimeMillis();log.info("获取JSON数据耗时:" + (time2 - time1) + "ms");//解析开始时间long start = System.currentTimeMillis();//开始解析(翻译字段内部的值凡是打了@Dict这玩意的都会被翻译)this.parsedictLabel(result);//解析结束时间long end = System.currentTimeMillis();log.info("解析注入JSON数据耗时:" + (end - start) + "ms");return result;}private void parsedictLabel(Object result) {if (result instanceof ResponseBean) {List<JSONObject> items = new ArrayList<>();Map<String, List<JSONObject>> objects = new HashMap<>();Map<String, JSONObject> jsonObject = new HashMap<>();ResponseBean responseBean = (ResponseBean) result;// 获取实际数据 ResponseBean.getDataObject data = responseBean.getData();// 处理data没有json数据问题if (Objects.isNull(data)) {return;}// 处理data是个集合if (data instanceof List) {for (Object object : (List<?>) data) {String json = convertJson(object);items.add(getDictAnnotation(json, object));}responseBean.setData(items);// 处理是map集合问题} else if (data instanceof Map) {//Object转MapMap<String, Object> map = JSONObject.parseObject(JSON.toJSONString(data));map.keySet().forEach(key -> {// 处理map value是集合问题if (map.get(key) instanceof List) {for (Object object : (List<?>) data) {String json = convertJson(object);objects.put(key, Collections.singletonList(getDictAnnotation(json, object)));}responseBean.setData(objects);// 处理map value是对象问题} else {Object object = map.get(key);String json = convertJson(object);jsonObject.put(key, getDictAnnotation(json, object));}responseBean.setData(jsonObject);});// 处理是对象问题} else {String json = convertJson(data);JSONObject item = getDictAnnotation(json, data);items.add(item);responseBean.setData(item);}}}/*** 翻译字典文本*/private String translateDictValue(String dictType, String key) {//如果key为空直接返回就好了if (isEmpty(key)) {return "";}StringBuffer textValue = new StringBuffer();//分割key值String[] keys = key.split(",");//循环keys中的所有值for (String k : keys) {String tmpValue = null;log.debug("字典key:" + k);if (k.trim().length() == 0) {continue; //跳过循环}tmpValue = dictService.getDictNameByCodeAndType(dictType, key);if (tmpValue != null) {if (!"".equals(textValue.toString())) {textValue.append(",");}textValue.append(tmpValue);}}//返回翻译的值return textValue.toString();}public static Field[] getAllFields(Object object) {Class<?> clazz = object.getClass();List<Field> 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) {return object == null || "".equals(object) || "null".equals(object);}public JSONObject getDictAnnotation(String json, Object object) {JSONObject item = JSONObject.parseObject(json);//解决继承实体字段无法翻译问题for (Field field : getAllFields(object)) {//解决继承实体字段无法翻译问题//如果该属性上面有@Dict注解,则进行翻译if (field.getAnnotation(Dict.class) != null) {//拿到注解的dictType属性的值String dictType = field.getAnnotation(Dict.class).dictType();//拿到注解的dictLabel属性的值String text = field.getAnnotation(Dict.class).dictLabel();//获取当前待翻译的值String key = String.valueOf(item.get(field.getName()));//翻译字典值对应的text值String textValue = translateDictValue(dictType, key);//DICT_TEXT_SUFFIX的值为,是默认值://public static final String DICT_TEXT_SUFFIX = "_dictLabel";log.debug("字典Val: " + textValue);log.debug("翻译字典字段:" + field.getName() + DICT_TEXT_SUFFIX + ": " + textValue);//如果给了文本名if (!StringUtils.isBlank(text)) {item.put(text, textValue);} else {//走默认策略item.put(field.getName() + DICT_TEXT_SUFFIX, textValue);}}}return item;}public String convertJson(Object object) {ObjectMapper mapper = new ObjectMapper();String json = "{}";try {//解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormatjson = mapper.writeValueAsString(object);} catch (JsonProcessingException e) {log.error("Json解析失败:" + e);}return json;}

 解决拦截所有的请求耗时过长问题

 @Pointcut("execution(* com.daimler..controller..*(..))")public void excudeService() {}

自定义切面注解来拦截莫一个controller接口


import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** 拦截controller接口数据进行翻译*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface InterceptInterface {}

SpringBoot字典翻译相关推荐

  1. springboot 字典翻译

    springboot 字典翻译 一.基于注解和jackson序列化实现字典翻译 二. 基于注解和aop实现字典翻译 本文主要介绍两种在项目中用到的字典翻译方式: 一.基于注解和jackson序列化实现 ...

  2. 字典翻译EasyTrans简单使用分享

    前言 最近太忙了,一直按在项目上摩擦,都没有时间写分享了.今天终于市把所有负责的模块都写完了,本次迭代引入了字典翻译,借这个机会顺便分享下. 一.什么是字典翻译 所谓的字典翻译其实简单理解就是一些不常 ...

  3. Element UI 实现字典翻译

    小白记录下element ui的学习过程. 这样的一个页面,需要将所有控件的label名称包括table的表头,都改成可根据字典翻译的 这是原本的写法 首先,需要从数据库中将字典的对象查出来 在页面渲 ...

  4. java 数据字典翻译_BeanUtils——JavaBean相互转换及字典翻译

    翻译JavaBean中带有@CacheFormat的属性/** * 翻译当前类中需要翻译的字典值 * * @param source 待翻译的对象 */ public static  void dat ...

  5. Jeecg-boot字典翻译改造

    一.找到字典切面类(DictAspect) 二.改造方法(parseDictText) 三.修改后的parseDictText方法,支持IPage.List.Object private void p ...

  6. jeecg-boot字典翻译改造(支持实体类详情查询自动翻译)

    找到字典切面类(DictAspect) 改造方法(parseDictText) 支持自动生成的列表接口/单个实体类查询翻译 代码如下: private void parseDictText(Objec ...

  7. java字典初始化_字典翻译注解讲解

    原理 使用拦截器,初始化时加载缓存到,使用时判断注解,根据注解解析缓存类,并用正则表达式,翻译后重写json数据,直到返回结果 使用 系统启动时,初始化查询字典,将字典缓存到redis中格式为 /** ...

  8. python怎么建立字典翻译_如何在python中使用字典将荷兰语翻译成英语

    我正试图翻译我是杰森使用这段代码,但当我使用它时,它什么也不会打印出来,除非我做一个像hello这样的单词,然后它会打印出guten tag,但就是这样.另外,我无法将输入数据转换为小写,以便与字典进 ...

  9. Springboot字典回显

    说明 在前后端分离开发的场景下,后端经常会需要将状态或者类型这样的数据以阿拉伯数字返回,比如1:生效,2:失效:3:发布中等等:以往我们的做法都是前后端沟通好前端通过数字和中文自己对应并显示.后端如果 ...

最新文章

  1. python核心-类-1
  2. 104. Maximum Depth of Binary Tree
  3. CentOS7安装iptables防火墙的方法
  4. HDU多校1 - 6955 Xor sum(字典树+贪心)
  5. springdata jpa单表操作crud
  6. 【转】RabbitMQ六种队列模式-5.主题模式
  7. Docker核心组件的关系
  8. 回溯递归算法----八皇后问题
  9. I00007 打印菱形字符图案
  10. 3D数学——Unity中的向量运算
  11. Git利用命令行提交代码步骤
  12. 服务器启动显示fr 01,X3850X5服务器无法开机故障处理-微码升级
  13. 【MATLAB基础】数据作图--imagesc
  14. mBio | 海洋所孙超岷组在深海原位验证了微生物介导的单质硫形成新通路
  15. apr 移植android平台,omap3530移植android4.0
  16. 音视频开发——概述(含TUTK demo iOS)
  17. html5 图片处理 开源,AlloyImage 基于 HTML5 的专业级图像处理开源引擎 - 文章教程...
  18. 嵌入式接口技术基础(粤嵌教学)
  19. 人能不能向计算机一样输入知识,电视机能不能做为计算机的显示器来使用
  20. 机器人行走的不同路径

热门文章

  1. keill5中用JLINK下载与调试程序
  2. Mysql基础11-MVCC机制
  3. keras数据增广并保存到本地文件夹
  4. ORA12541: TNS:no listener解决办法
  5. TensorFlow—GPU版本运行报错:failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
  6. Safari浏览器中input 光标lineheight失效 不居中
  7. zencart1.55手把手教你开发stripe支付插件
  8. 寒门难再出贵子(5),一篇值得思考的文章
  9. vxworks常用调试命令
  10. 基于SSM+Python的仿Panli海外代购平台毕业设计(SSM毕业设计)