构建VO字典转换通用方法

创建翻译注解

/**
 * 字典vo翻译
 * @author: Gang_Wang
 * @description
 * @Date: 2022/10/18 上午9:28
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface DictTransform {

    /**
     * 翻译目标值
     * @return
     */
    String target();

    /**
     * 字典字典值
     * @return
     */
    String dictValue();

    /**
     * 字典服务Service
     * @return
     */
    String service();

}

创建翻译工具类

/**
 * @author: Gang_Wang
 * @description
 * @Date: 2022/10/18 上午9:35
 */
@Slf4j
public class BeanHelpUtils {

    public static <T> void translation(T t) {
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(DictTransform.class)) {
                String target = field.getAnnotation(DictTransform.class).target();
                String dictValue = field.getAnnotation(DictTransform.class).dictValue();
                String service = field.getAnnotation(DictTransform.class).service();
                DictService dictService = SpringContextHolder.getBean(service, DictService.class);
                if (dictService != null) {
                    //获得字典编码
                    PropertyDescriptor source = null;
                    try {
                        source = new PropertyDescriptor(target, t.getClass());
                        Object invoke = source.getReadMethod().invoke(t);
                        Object result = dictService.getValue(dictValue, invoke);
                        PropertyDescriptor targetResult = new PropertyDescriptor(field.getName(), t.getClass());
                        targetResult.getWriteMethod().invoke(t, result);
                    } catch (Exception e) {
                        log.error(e.toString());
                        e.printStackTrace();
                        throw new BizException(ErrorCodeMsg.ERROR_OP0402.getCode(), ErrorCodeMsg.ERROR_OP0402.getMessage());
                    }
                }
            }
        }
    }


    public static <T> void translation(List<T> collect) {
        for (T t : collect) {
            translation(t);
        }
    }
    /**
     * // 调用分页转换,自动翻译
     * ...
     * IPage<EmployeePO> poPage = employeeMapper.selectPage(page, new QueryWrapper<EmployeePO>().lambda()
     *                 .eq(...
     * return BeanHelpUtils.pageTransform(poPage, EmployeeVO::new);
     * // 或直接调用翻译
     * List<EmployeeVO> records = poPage.getRecords();
     * BeanHelpUtils.translation(records);
     * return records;
     */
    /**
     * 分页复制
     */
    public static <T, E> IPage<T> pageTransform(IPage<E> page, Function<E, T> sup) {
        if (page == null || page.getRecords() == null){ return null;}
        List<T> collect = page.getRecords().stream().map(sup).collect(Collectors.toList());
        translation(collect);
        return new Page<T>(page.getCurrent(), page.getSize(), page.getTotal()).setRecords(collect);
    }

/**
 *  DictService 字典接口
 * @author: Gang_Wang
 * @description
 * @Date: 2022/10/18 上午9:55
 */
public interface DictService {
    Object getValue(String dicValue,Object key);
}

具体使用方法

    /**
     * 告警类型	            0:备件告警	            1:设备告警	            2:数据告警
     */
    @ApiModelProperty(value = "告警类型 0:备件告警1:设备告警  2:数据告警")
    private Integer ruleType;

    @ApiModelProperty(value = "告警类型中文")
    @DictTransform(target = "ruleType", dictValue= GeneralConstants.BaseSysConfigConfigClass.ALARM_TYPE, service = "baseSysConfigServiceImpl")
    private String ruleTypeName;

下面是经过改良的方法:

package com.example.demo.test_class;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.*;

/**
 * Bean翻译工具类
 * @author: Gang_Wang
 * @description
 * @Date: 2022/10/18 上午9:35
 */
@Slf4j
public class BeanTranslateUtils {

    /**
     * 翻译单个Object里多个字典值
     * @param t
     * @param <T>
     */
    public static <T> void translation(T t) {
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(DictTransform.class)) {
                String target = field.getAnnotation(DictTransform.class).target();
                String dictValue = field.getAnnotation(DictTransform.class).dictValue();
                String service = field.getAnnotation(DictTransform.class).service();
                Class<?> serviceClass = field.getAnnotation(DictTransform.class).serviceClass();
                DictService dictService = null;
                if(StringUtils.isNotEmpty(service)){
                    dictService = SpringContextHolder.getBean(service, DictService.class);
                }else{
                    dictService= (DictService)SpringContextHolder.getBean(serviceClass);
                }
                if (dictService != null) {
                    //获得字典编码
                    PropertyDescriptor source = null;
                    try {
                        source = new PropertyDescriptor(target, t.getClass());
                        Object invoke = source.getReadMethod().invoke(t);
                        Object result = dictService.getValue(dictValue, invoke);
                        PropertyDescriptor targetResult = new PropertyDescriptor(field.getName(), t.getClass());
                        targetResult.getWriteMethod().invoke(t, result);
                    } catch (Exception e) {
                        log.error(e.toString());
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    @SneakyThrows
    public static <T> void translation(List<T> collect) {
        if(CollectionUtils.isEmpty(collect)){
            return ;
        }

        //Map<字段名称,字典值Code集合>
        Map<String,List<Object>> dictValueMap = new HashMap<>();
        //Map<字段名称,字典组>
        Map<String,String> dictGroupMap = new HashMap<>();
       //Map<字段名称,实现类名称>
        Map<String,DictService> dictServiceMap = new HashMap<>();
        //Map<字段名称,字典值Name集合>
        Map<String,List<DictTranslateVo>> dictNameMap = new HashMap<>();
        //初始化
        T t = collect.get(0);
        initHashMap(t,dictValueMap,dictGroupMap,dictServiceMap);
        //补充数据
        for(T t1 : collect){
            for(Map.Entry<String,List<Object>> entry : dictValueMap.entrySet()){
                PropertyDescriptor source = new PropertyDescriptor(entry.getKey(), t.getClass());
                Object invoke = source.getReadMethod().invoke(t1);
                entry.getValue().add(invoke);
            }
        }
        for(Map.Entry<String,DictService> entry : dictServiceMap.entrySet()){
            DictService dictService =  entry.getValue();
            List<DictTranslateVo> result = dictService.getValueList(dictGroupMap.get(entry.getKey()), dictValueMap.get(entry.getKey()));
            //dictNameMap添加
            dictNameMap.put(entry.getKey(), result);
        }
        //循环查询数据
        for(T t2 : collect){
            Field[] fields2 = t2.getClass().getDeclaredFields();
            for (Field field : fields2) {
                if (field.isAnnotationPresent(DictTransform.class)) {
                    Object result = "";
                    String target = field.getAnnotation(DictTransform.class).target();
                    PropertyDescriptor source = new PropertyDescriptor(target, t2.getClass());
                    Object invoke = source.getReadMethod().invoke(t2);
                    List<DictTranslateVo> dictTranslateVoList= dictNameMap.get(target);
                    if(CollectionUtils.isNotEmpty(dictTranslateVoList)){
                        Optional<DictTranslateVo> optional= dictTranslateVoList.stream().filter(p->invoke.equals(p.getCode())).findAny();
                        if(optional.isPresent()){
                            result = optional.get().getName();
                        }
                        PropertyDescriptor targetResult = new PropertyDescriptor(field.getName(), t2.getClass());
                        targetResult.getWriteMethod().invoke(t2, result);
                    }
                }
            }
        }
    }


    /**
     * 初始化集合字典
     * @param t          单个对象
     * @param dictValueMap   Map<字段名称,字典值Code集合>
     * @param dictGroupMap   Map<字段名称,字典组>
     * @param dictServiceMap  <字段名称,实现类名称>
     * @param <T>
     */
    private static <T> void initHashMap(T t, Map<String,List<Object>> dictValueMap,Map<String,String> dictGroupMap,
                                        Map<String,DictService> dictServiceMap) {
        Field[] fields = t.getClass().getDeclaredFields();
        for(Field field: fields){
            if (field.isAnnotationPresent(DictTransform.class)) {
                String target = field.getAnnotation(DictTransform.class).target();
                String dictValue = field.getAnnotation(DictTransform.class).dictValue();
                //获得字典编码
                String service = field.getAnnotation(DictTransform.class).service();
                Class<?> serviceClass = field.getAnnotation(DictTransform.class).serviceClass();
                DictService dictService = null;
                if(StringUtils.isNotEmpty(service)){
                    dictService = SpringContextHolder.getBean(service, DictService.class);
                }else{
                    dictService= (DictService)SpringContextHolder.getBean(serviceClass);
                }
                dictValueMap.put(target,new ArrayList<>());
                dictGroupMap.put(target, dictValue);
                dictServiceMap.put(target,dictService);
            }
        }
    }





}

package com.example.demo.test_class;

import java.util.List;

/**
 *  DictService 字典接口
 * @author: Gang_Wang
 * @description
 * @Date: 2022/10/18 上午9:55
 */
public interface DictService {

    /**
     *  获取对应字典值
    * @Description:  获取对应字典值
     * @param dicValue:  匹配字典表的组
     * @param key:       匹配的字典值
    * @Param: [dicValue, key]
    * @return: java.lang.Object
    * @Author: Gang_Wang
    * @Date: 2023/9/17
    */
    Object getValue(String dicValue,Object key);


    
    /** 
     * 获取对应字典值 集合
    * @Description:    获取对应字典值
     * @param dicValue:  匹配字典表的组
    * @param keys:       匹配的字典值
    * @Param: [dicValue, keys] 
    * @return: java.util.List<com.example.demo.test_class.DictTranslateVo> 
    * @Author: Gang_Wang 
    * @Date: 2023/9/17 
    */ 
    List<DictTranslateVo> getValueList(String dicValue, List<Object> keys);
}

package com.example.demo.test_class;

import java.lang.annotation.*;

/**
 * 字典vo翻译
 * @author: Gang_Wang
 * @description
 * @Date: 2022/10/18 上午9:28
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface DictTransform {

    /**
     * 翻译目标值
     * @return
     */
    String target();

    /**
     * 字典字典值(使用了字典表,会使用该属性)
     * @return
     */
    String dictValue() default "";

    /**
     * 字典服务Service
     * @return
     */
    String service() default "";

    /**
     * 字典服务Service 动态类
     * @return
     */
    Class<?> serviceClass();

}

package com.example.demo.test_class;

import lombok.Data;

/**
 * @author: Gang_Wang
 * @description
 * @Date: 2023/9/17 下午1:05
 */
@Data
public class DictTranslateVo {

    /**
     * 编码
     */
    private Object Code;

    /**
     * 名称
     */
    private Object name;
}

package com.example.demo.test_class;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * Spring 工具类
 *
 * @author zlf
 * @date 2022-09-23
 */
@Slf4j
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = null;

    /**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 实现ApplicationContextAware接口, 注入Context到静态变量中.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextHolder.applicationContext = applicationContext;
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        if (applicationContext == null){
            return null;
        }
        return applicationContext.getBean(name, requiredType);
    }

    /**
     * 清除SpringContextHolder中的ApplicationContext为Null.
     */
    public static void clearHolder() {
        if (log.isDebugEnabled()) {
            log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
        }
        applicationContext = null;
    }

    /**
     * 发布事件
     *
     * @param event 事件
     */
    public static void publishEvent(ApplicationEvent event) {
        if (applicationContext == null) {
            return;
        }
        applicationContext.publishEvent(event);
    }

    /**
     * 实现DisposableBean接口, 在Context关闭时清理静态变量.
     */
    @Override
    @SneakyThrows
    public void destroy() {
        SpringContextHolder.clearHolder();
    }
}

package com.example.demo.test_class;

import com.example.demo.service.impl.DemoServiceBeijing;
import com.example.demo.service.impl.DemoServiceShanghai;
import lombok.Data;

/**
 * @author: Gang_Wang
 * @description
 * @Date: 2023/9/15 下午5:26
 */
@Data
public class TestVo {

    private String code;

    @DictTransform(target = "code", serviceClass = DemoServiceShanghai.class)
    private String name;


    private String code1;

    @DictTransform(target = "code1", serviceClass = DemoServiceBeijing.class)
    private String name1;
}

package com.example.demo.service.impl;

import com.example.demo.service.IDemoService;
import com.example.demo.test_class.DictService;
import com.example.demo.test_class.DictTranslateVo;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class DemoServiceBeijing implements IDemoService, DictService {
    @Override
    public void doSomething() {
        System.out.println("北京的业务实现");
    }

    @Override
    public Object getValue(String dicValue, Object key) {
        return null;
    }

    @Override
    public List<DictTranslateVo> getValueList(String dicValue, List<Object> keys) {
        List<DictTranslateVo> DictTranslateVoList = new ArrayList<>();
        DictTranslateVo vo1 = new DictTranslateVo();
        DictTranslateVo vo2 = new DictTranslateVo();

        vo1.setCode("字典值1");
        vo1.setName("字典值1-对应名称1");
        vo2.setCode("字典值2");
        vo2.setName("字典值2--对应名称2");

        DictTranslateVoList.add(vo1);
        DictTranslateVoList.add(vo2);
        return DictTranslateVoList;
    }


}

    @GetMapping("/skywalking/warn/re/klllo111111111")
    public void re111222() {
      /*  TestVo vo = new TestVo();
        BeanTranslateUtils.translation(vo);
        System.out.println(vo);*/
        List<TestVo> list = new ArrayList<>();
        TestVo vo1 = new TestVo();
        vo1.setCode("字典值1");
        vo1.setCode1("字典值2");
        TestVo vo2 = new TestVo();
        vo2.setCode("字典值3");
        vo2.setCode1("字典值4");
        list.add(vo1);
        list.add(vo2);

        BeanTranslateUtils.translation(list);
        System.out.println(list);
        return ;
    }
[TestVo(code=字典值1, name=null, code1=字典值2, name1=字典值2--对应名称2), TestVo(code=字典值3, name=null, code1=字典值4, name1=)]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值