【JAVA日常】关于jeecgBoot @Dict注解的使用不生效问题

发布时间 2023-09-11 15:13:17作者: 三岁6

项目中后端使用jeecgBoot开发,最近正好遇到一些关于改造和使用@dict字典注解的问题,正好记录一下,以防忘记。

1、注解不生效问题1

今天公司同事问,说这个注解加上了怎么还不起作用呢。
我们就检查了代码中的使用。注解的添加以及使用都正常,然后排查发现接口调用时未执行字典的切面,那么问题基本就清晰了,检查了Dict注解的切点

public * org.jeecg.modules..*.*Controller.*(..))"

而在他的实际代码中,他的controller层的命名为 *ControllerApp,问题就出在这里了。

解决办法有两个要么同事代码的命名来进行修改切点配置,要么就遵循jeecgBoot框架的切点配置。

2、注解切面处理字典只兼容IPage

这个问题吧,也不算是问题,就是在使用@Dict注解的过程中 总会遇到一些时候我们并不需要返回IPage,但是又想进行字典翻译的情况。
但是翻看了官方的切面代码

(代码位置:org/jeecg/modules/system/aspect/DictAspect.java)

发现官方仅支持当Result的返回类型为IPage时才进行处理,并不适用于我们需要的Map、List、对象、Json类型。

只好对该切面进行改造。
注意:该方法并不适用所有,谨慎使用。
下面来讲一下改造方法:
在上图中的if方法后 增加一个else方法,放入下方代码

else if (!(((Result)result).getResult() instanceof String)){
                /**
                 * 2023-07-18处理  @Dict注解增加支持 LIST、MAP、实体对象的字典翻译
                 * sansui
                 */
                //取出结果集
                Object object=  (Object) ((Result) result).getResult();
                if(oConvertUtils.isEmpty(object)){
                    return result;
                }
                Class<?> aClass = ((Result) result).getResult().getClass();
                if ("java.util.HashMap".equals(aClass.getName())){
                    //将map转换为集合在转换为map
                    Map<String, Object> mapset = new HashMap<>();
                    Map<String,Object> map=  (Map<String,Object>) object;
                    for (String s : map.keySet()) {
                        Object a1 = map.get(s);
                        List<Object> records=new ArrayList<>();
                        Class<?> aClass1 = a1.getClass();
                        if ("java.util.ArrayList".equals(aClass1.getName())){
                            records = (ArrayList)map.get(s);
                        }else{
                            records = oConvertUtils.objToList(a1, Object.class);
                        }
                        Boolean hasDict= checkHasDict(records);
                        if(!hasDict){
                            return result;
                        }
                        List<JSONObject> dictText = getDictText(records);
                        mapset.put(s,dictText);
                    }
                    ((Result) result).setResult(mapset);
                }else if (((Result)result).getResult() instanceof List){
                    List<Object> records = oConvertUtils.objToList(object, Object.class);
                    //判断是否含有字典注解,没有注解返回-----
                    Boolean hasDict= checkHasDict(records);
                    if(!hasDict){
                        return result;
                    }
                    List<JSONObject> dictText = getDictText(records);
                    ((Result) result).setResult(dictText);
                }else {
                    // 取出结果
                    Object record = ((Result)result).getResult();

                    if (record instanceof Boolean) {
                        // record是布尔类型
                        // 进行相应的操作
                        return result;
                    }

                    log.debug(" __ 进入字典翻译切面 DictAspect —— ");
                    // update-end--Author:zyf -- Date:20220606 ----for:【VUEN-1230】 判断是否含有字典注解,没有注解返回-----
                    String json = "{}";
                    try {
                        // 解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                        json = objectMapper.writeValueAsString(record);
                    } catch (JsonProcessingException e) {
                        log.error("json解析失败" + e.getMessage(), e);
                    }
                    JSONObject item = JSONObject.parseObject(json, Feature.OrderedField);
                    for (Field field : oConvertUtils.getAllFields(record)) {
                        String value = item.getString(field.getName());
                        if (oConvertUtils.isEmpty(value)) {
                            continue;
                        }
                        // update-end--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                        if (field.getAnnotation(Dict.class) != null) {
                            String code = field.getAnnotation(Dict.class).dicCode();
                            String text = field.getAnnotation(Dict.class).dicText();
                            String table = field.getAnnotation(Dict.class).dictTable();
                            String key = String.valueOf(item.get(field.getName()));

                            String fieldDictCode = code;
                            if (!org.apache.commons.lang.StringUtils.isEmpty(table)) {
                                fieldDictCode = String.format("%s,%s,%s", table, text, code);
                            }

                            String textValue = this.translateDictValue(code, text, table,key);
                            log.debug(" 字典Val : " + textValue);
                            log.debug(
                                    " __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);

                            // TODO-sun 测试输出,待删
                            log.debug(" ---- dictCode: " + fieldDictCode);
                            log.debug(" ---- value: " + value);
                            log.debug(" ----- text: " + textValue);

                            item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                        }
                    }
                    ((Result)result).setResult(item);
                }
            } 

其中 使用到了一个 新增方法,当前类 随便找个地方放一下就行。

/**
     传入集合 翻译字典值
     **/
    private List<JSONObject> getDictText(List<Object> records){
        List<JSONObject> items = new ArrayList<>();
        //step.1 筛选出加了 Dict 注解的字段列表
        List<Field> dictFieldList = new ArrayList<>();
        // 字典数据列表, key = 字典code,value=数据列表
        Map<String, List<String>> dataListMap = new HashMap<>(5);


        log.debug(" __ 进入字典翻译切面 DictAspect —— " );
        //update-end--Author:zyf -- Date:20220606 ----for:【VUEN-1230】 判断是否含有字典注解,没有注解返回-----
        for (Object record : records) {
            String json="{}";
            try {
                //update-begin--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
                //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                json = objectMapper.writeValueAsString(record);
                //update-end--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
            } catch (JsonProcessingException e) {
                log.error("json解析失败"+e.getMessage(),e);
            }
            //update-begin--Author:scott -- Date:20211223 ----for:【issues/3303】restcontroller返回json数据后key顺序错乱 -----
            JSONObject item = JSONObject.parseObject(json, Feature.OrderedField);
            //update-end--Author:scott -- Date:20211223 ----for:【issues/3303】restcontroller返回json数据后key顺序错乱 -----

            //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
            //for (Field field : record.getClass().getDeclaredFields()) {
            // 遍历所有字段,把字典Code取出来,放到 map 里
            for (Field field : oConvertUtils.getAllFields(record)) {
                String value = item.getString(field.getName());
                if (oConvertUtils.isEmpty(value)) {
                    continue;
                }
                //update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                if (field.getAnnotation(Dict.class) != null) {
                    if (!dictFieldList.contains(field)) {
                        dictFieldList.add(field);
                    }
                    String code = field.getAnnotation(Dict.class).dicCode();
                    String text = field.getAnnotation(Dict.class).dicText();
                    String table = field.getAnnotation(Dict.class).dictTable();

                    List<String> dataList;
                    String dictCode = code;
                    if (!StringUtils.isEmpty(table)) {
                        dictCode = String.format("%s,%s,%s", table, text, code);
                    }
                    dataList = dataListMap.computeIfAbsent(dictCode, k -> new ArrayList<>());
                    this.listAddAllDeduplicate(dataList, Arrays.asList(value.split(",")));
                }
                //date类型默认转换string格式化日期
                //update-begin--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
                //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()))));
                //}
                //update-end--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
            }
            items.add(item);
        }

        //step.2 调用翻译方法,一次性翻译
        Map<String, List<DictModel>> translText = this.translateAllDict(dataListMap);

        //step.3 将翻译结果填充到返回结果里
        for (JSONObject record : items) {
            for (Field field : dictFieldList) {
                String code = field.getAnnotation(Dict.class).dicCode();
                String text = field.getAnnotation(Dict.class).dicText();
                String table = field.getAnnotation(Dict.class).dictTable();

                String fieldDictCode = code;
                if (!StringUtils.isEmpty(table)) {
                    fieldDictCode = String.format("%s,%s,%s", table, text, code);
                }

                String value = record.getString(field.getName());
                if (oConvertUtils.isNotEmpty(value)) {
                    List<DictModel> dictModels = translText.get(fieldDictCode);
                    if(dictModels==null || dictModels.size()==0){
                        continue;
                    }

                    String textValue = this.translDictText(dictModels, value);
                    log.debug(" 字典Val : " + textValue);
                    log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);

                    // TODO-sun 测试输出,待删
                    log.debug(" ---- dictCode: " + fieldDictCode);
                    log.debug(" ---- value: " + value);
                    log.debug(" ----- text: " + textValue);
                    log.debug(" ---- dictModels: " + JSON.toJSONString(dictModels));

                    record.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                }
            }
        }
        return items;
    }

欧克,在测试就支持实体对象进行翻译了。