其他分享
首页 > 其他分享> > 适配若依框架的字典翻译

适配若依框架的字典翻译

作者:互联网

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