ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

适配若依框架的字典翻译

2022-05-27 17:33:49  阅读:266  来源: 互联网

标签:适配 springframework 若依 org import er data annotation 字典


package cn.crservice.er.common.annotation;

import java.lang.annotation.*;

/**
 * 字典翻译注解
 *
 * @author Li Yangdi
 * @since 2022-05-25
 */
@Documented
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DictLabel {

    // 字典类型,对应 sys_dict_data.dict_type 字段
    String value();
}
package cn.crservice.er.framework.aspectj;

import cn.crservice.er.common.annotation.DictLabel;
import cn.crservice.er.common.core.domain.AjaxResult;
import cn.crservice.er.common.core.domain.entity.SysDictData;
import cn.crservice.er.common.core.page.TableDataInfo;
import cn.crservice.er.common.utils.reflect.ReflectUtils;
import cn.crservice.er.system.service.ISysDictTypeService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 字典翻译
 *
 * @author Li Yangdi
 * @since 2022-05-25
 */
@Slf4j
@Aspect
@Component
public class DictTranslator {

    @Autowired
    private ISysDictTypeService sysDictTypeService;

    @AfterReturning(pointcut = "(@within(org.springframework.web.bind.annotation.RestController)) " +
            "&& (@annotation(org.springframework.web.bind.annotation.GetMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.PostMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.PutMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.DeleteMapping))",
            returning = "ret")
    public void translate(Object ret) {
        if (ret instanceof AjaxResult) {
            recursionTranslate((AjaxResult) ret);
        } else if (ret instanceof TableDataInfo) {
            TableDataInfo tableDataInfo = (TableDataInfo) ret;
            List<?> rows = tableDataInfo.getRows();
            if (rows == null || rows.size() == 0) {
                return;
            }
            recursionTranslateCollection(rows);
        }
    }

    private void recursionTranslate(AjaxResult result) {
        Object data = result.get(AjaxResult.DATA_TAG);
        if (data == null) {
            return;
        }
        if (Collection.class.isAssignableFrom(data.getClass())) {
            recursionTranslateCollection((Collection<?>) data);
        } else {
            recursionTranslateObj(data);
        }
    }

    private void recursionTranslateCollection(Collection<?> collection) {
        log.trace("recursionTranslate for Collection");
        if (collection == null) {
            return;
        }
        collection.forEach(this::recursionTranslateObj);
    }

    private void recursionTranslateObj(Object data) {
        final String DICT_LABEL_PROP_SUFFIX = "Label";
        log.trace("recursionTranslate for Object");
        if (data == null) {
            return;
        }
        if (Collection.class.isAssignableFrom(data.getClass())) {
            recursionTranslateCollection((Collection<?>) data);
            return;
        }
        List<Field> fields = new ArrayList<>(Arrays.asList(data.getClass().getDeclaredFields()));
        Class<?> parent = data.getClass().getSuperclass();
        while (!parent.isAssignableFrom(Object.class)) {
            fields.addAll(Arrays.asList(parent.getDeclaredFields()));
            parent = parent.getSuperclass();
        }
        for (Field field : fields) {
            Class<?> fieldType = field.getType();
            if (Collection.class.isAssignableFrom(fieldType)) {
                recursionTranslateCollection(ReflectUtils.invokeGetter(data, field.getName()));
                continue;
            }
            field.setAccessible(true);
            DictLabel dictLabel = field.getAnnotation(DictLabel.class);
            if (dictLabel == null || !String.class.isAssignableFrom(fieldType)) {
                continue;
            }
            String dictType = dictLabel.value();
            String dictValue = null;
            try {
                dictValue = (String) field.get(data);
            } catch (IllegalAccessException ex) {
                log.error("Failed translate dict", ex);
            }
            if (!StringUtils.hasText(dictType) || !StringUtils.hasText(dictValue)) {
                log.warn("dict translate, but key or value is empty");
                continue;
            }
            List<SysDictData> dictData = sysDictTypeService.selectDictDataByType(dictType);
            if (dictData == null || dictData.size() == 0) {
                log.warn("Dict {} data not exists", dictType);
                continue;
            }
            Map<String, String> dictValue2Label = dictData.stream().collect(
                    Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            ReflectUtils.invokeSetter(data,
                    field.getName() + DICT_LABEL_PROP_SUFFIX,
                    dictValue2Label.get(dictValue));
        }
    }
}

用法:其中 deptTypeLabel 仅为实体字段,非数据库存在,标注了 DictLabel 注解的属性一定有个 setter 名 + Label 的属性

    /**
     * 机构类型,关联字典 dept_type
     */
    @DictLabel("dept_type")
    private String deptType;
    private String deptTypeLabel;

若依这框架代码真是稀烂

标签:适配,springframework,若依,org,import,er,data,annotation,字典
来源: https://www.cnblogs.com/seliote/p/16318412.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有