目录

  • 事件起因
  • 给实体的一个属性自定义一个注解
  • Dict文件、Aspect文件的内容:
  • 代码讲解和描述
  • Dict文件
  • Aspect文件:
  • 参考


事件起因

在修改一个老项目的时候,用户和资产导入和导出功能有部分字段都执行了翻译操作,数据库中存储的是一个字符串id 采用,号隔开存储的一个字符串或该资产关联其他部门信息的关联id,这样的信息在导入时需要判断这些是否是当前系统中已经拥有的部门 并将该字段转义为对应的id 存储进入数据库中,然后在导出时,又要将对应的id字段翻译为对应的部门名(毕竟用户想看的是某个人与这些部门之间的关系,而不是某个人与这些部门id之间的关系,再说他也看不懂啊) 于是为了实现这个需求,就在请教了几个老员工(我的强哥还是强啊)的情况下,知道了使用这个aop切点编程来对数据进行翻译

给实体的一个属性自定义一个注解

Dict文件、Aspect文件的内容:

Dict文件内容:

java 如何让返回值都是大写 java返回值怎么写_java 如何让返回值都是大写


具体代码:

package cn.com.wewin.common.aspect.annotation;

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 ExcelDict {
    /**
     * 方法描述:  数据code
     * @return 返回类型: String
     */
    String dicCode();

    /**
     * 方法描述:  数据Text
     * @return 返回类型: String
     */
    String dicText() default "";

    /**
     * 方法描述: 数据字典表
     * @return 返回类型: String
     */
    String dictTable() default "";
}

Aspect文件内容:

java 如何让返回值都是大写 java返回值怎么写_数据筛选_02


具体代码如下:

package cn.com.wewin.modules.system.aspect;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.com.wewin.common.api.vo.Result;
import cn.com.wewin.common.aspect.annotation.ExcelDict;
import cn.com.wewin.common.constant.CommonConstant;
import cn.com.wewin.common.util.oConvertUtils;
import cn.com.wewin.modules.system.service.ISysDictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;

@Aspect
@Component
@Slf4j
public class ExcelDictAspect {
    @Autowired
    private ISysDictService dictService;
    // 定义切点Pointcut
    @Pointcut("execution(* cn.com.wewin.modules.asset.controller.AssetController.exportXls(..))")
    public void assetExportPointCut() {
    }
    @Pointcut("execution(* cn.com.wewin.modules.system.controller.SysUserController.exportXls(..))")
    public void userExcelExportPointCut() {
    }
    @Around("assetExportPointCut()||userExcelExportPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
    	long time1=System.currentTimeMillis();
        Object result = pjp.proceed();
        long time2=System.currentTimeMillis();
        log.debug("获取JSON数据 耗时:"+(time2-time1)+"ms");
        long start=System.currentTimeMillis();
        this.parseDictText(result);
        long end=System.currentTimeMillis();
        log.debug("解析注入JSON数据  耗时"+(end-start)+"ms");
        return result;
    }

    /**
     * 本方法针对返回对象为Result 的IPage的分页列表数据进行动态字典注入
     * 字典注入实现 通过对实体类添加注解@ExcelDict 来标识需要的字典内容,字典分为单字典code即可 ,table字典 code table text配合使用与原来jeecg的用法相同
     * 示例为SysUser   字段为sex 添加了注解@ExcelDict(dicCode = "sex") 会在字典服务立马查出来对应的text 然后在请求list的时候将这个字典text,已字段名称加_dictText形式返回到前端
     * 例输入当前返回值的就会多出一个sex_dictText字段
     * {
     *      sex:1,
     *      sex_dictText:"男"
     * }
     * 前端直接取值sext_dictText在table里面无需再进行前端的字典转换了
     *  customRender:function (text) {
     *               if(text==1){
     *                 return "男";
     *               }else if(text==2){
     *                 return "女";
     *               }else{
     *                 return text;
     *               }
     *             }
     *             目前vue是这么进行字典渲染到table上的多了就很麻烦了 这个直接在服务端渲染完成前端可以直接用
     * @param result
     */
    private void parseDictText(Object result) {
        if (result instanceof ModelAndView) {

                List<JSONObject> items = new ArrayList<>();
                for (Object record : ((List) ((ModelAndView) result).getModel().get(new String("data")))) {
                    ObjectMapper mapper = new ObjectMapper();
                    String json="{}";
                    try {
                        //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
                         json = mapper.writeValueAsString(record);
                    } catch (JsonProcessingException e) {
                        log.error("json解析失败"+e.getMessage(),e);
                    }
                    JSONObject item = JSONObject.parseObject(json);
                    //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                    //for (Field field : record.getClass().getDeclaredFields()) {
                    for (Field field : oConvertUtils.getAllFields(record)) {
                    //update-end--Author:scott  -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
                        if (field.getAnnotation(ExcelDict.class) != null) {
                            String code = field.getAnnotation(ExcelDict.class).dicCode();
                            String text = field.getAnnotation(ExcelDict.class).dicText();
                            String table = field.getAnnotation(ExcelDict.class).dictTable();
                            String key = String.valueOf(item.get(field.getName()));

                            String translateTextById = null;
                            if(key.contains(StringPool.COMMA)){
                                //字符串中含有逗号 说明这是一个由多个id组成的字符串
                                String[] ids = key.split(StringPool.COMMA);
                                StringBuilder temp = new StringBuilder();
                                for(String id:ids){
                                    String temp2 = translateDictValue(code, text, table, id);
                                    if("".equals(temp.toString())){
                                        //加入的第一个 字符串 前无 , 号
                                        temp.append(temp2);
                                    }
                                    else{
                                        //加入 , 号和下一个id转换出来的翻译名
                                        temp.append(StringPool.COMMA).append(temp2);
                                    }
                                }
                                //遍历完所有id并翻译后转换为所需要的字符串
                                translateTextById = temp.toString();
                            }
                            else {
                                //无 , 号  单个id进行翻译
                                translateTextById = translateDictValue(code, text, table, key);
                            }

                            log.debug(" 字典Val : "+ translateTextById);
                            log.debug(" __翻译字典字段__ "+field.getName()+": "+ translateTextById);
                            item.put(field.getName(), translateTextById);
                        }
                        //date类型默认转换string格式化日期
//                        if (field.getType().getName().equals("java.util.Date")&&item.get(field.getName())!=null){
//                            SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                            item.put(field.getName(), aDate.format(((Date) item.get(field.getName()))));
//                        }
                    }
                    items.add(item);
                }
                ((ModelAndView) result).addObject(NormalExcelConstants.DATA_LIST, items);
        }

    }

    /**
     *  翻译字典文本
     * @param code
     * @param text
     * @param table
     * @param key
     * @return
     */
    private String translateDictValue(String code, String text, String table, String key) {
    	if(oConvertUtils.isEmpty(key)) {
    		return null;
    	}
        StringBuffer textValue=new StringBuffer();
        String[] keys = key.split(",");
        for (String k : keys) {
            String tmpValue = null;
            log.debug(" 字典 key : "+ k);
            if (k.trim().length() == 0) {
                continue; //跳过循环
            }
            if (!StringUtils.isEmpty(table)){
                log.debug("--DictAspect------dicTable="+ table+" ,dicText= "+text+" ,dicCode="+code);
                tmpValue= dictService.queryTableDictTextByKey(table,text,code,k.trim());
            }else {
                tmpValue = dictService.queryDictTextByKey(code, k.trim());
            }

            if (tmpValue != null) {
                if (!"".equals(textValue.toString())) {
                    textValue.append(",");
                }
                textValue.append(tmpValue);
            }

        }
        return textValue.toString();
    }
}

然后在实体上书写注解:

java 如何让返回值都是大写 java返回值怎么写_aop_03

代码讲解和描述

Dict文件

该文件主要作用是用于定义 注解的接口,

java 如何让返回值都是大写 java返回值怎么写_aop_04


代码中该注解接口存在三个属性,但是写法类似于接口函数方法

String dicCode();
    /**
     * 方法描述:  数据Text
     * @return 返回类型: String
     */
    String dicText() default "";
    /**
     * 方法描述: 数据字典表
     * @return 返回类型: String
     */
    String dictTable() default "";

然后在实体上写的注解就是这三个方法的内容 dicText() 和dictTable()存在默认值 是一个空字符串,

java 如何让返回值都是大写 java返回值怎么写_java_05

Aspect文件:

定义切点:

java 如何让返回值都是大写 java返回值怎么写_java 如何让返回值都是大写_06


如上图可知定义多个切点时 可以在@Around注解中采用 “||” 进行连接, 以此来实现同一个处理过程接受多个切点的调用,这样的多个切点指定的函数也可以在不同的包路径下在parseDictText里进行具体的操作 比如翻译和具体的数据筛选之类的操作

java 如何让返回值都是大写 java返回值怎么写_aop_07


先使用instanceof判断一下是哪种数据,当多个数据格式传入时,可以用if else 判断后分别处理对应的数据

然后就是遍历这个数据列表,判断每个对象的每个字段是否有@ExcelDict注解,有注解的就实现翻译操作

java 如何让返回值都是大写 java返回值怎么写_java 如何让返回值都是大写_08

对应的翻译函数调用:

java 如何让返回值都是大写 java返回值怎么写_java_09


执行翻译操作:

java 如何让返回值都是大写 java返回值怎么写_切点编程_10

参考