SpringBoot字典翻译

字典注解:

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";

    @Resource
    private 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.getData
            Object 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转Map
                Map<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类的@JsonFormat
            json = 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 {

}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悲伤酸菜鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值