Spring AOP实现Mapper层查询返回重新赋值

需求:

针对查询返回的数据,在数据库层处理可能会影响到性能,在考虑性能及维护方便的情况下,采用AOP实现

1,自定义注解

java 复制代码
import java.lang.annotation.*;

/**
 * 针对 mapper层返回值 按照一定规则进行特殊处理后返回
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MapperReturnData {
    /**
     * 指定执行规则的方法,默认方法为:transferReturnData
     * @return
     */
    String method() default "transferReturnData";
    Class<? extends MapperReturnDataInterface> operation();
}

2,定义公共业务处理接口

java 复制代码
/**
 * 不同的业务场景 其 针对返回值 解析处理规则不同,须根据自身情况实现该接口
 * @param <T>
 */
public interface MapperReturnDataInterface<R> {

    R transferReturnData(Object request);

}

3,编写AOP核心实现

java 复制代码
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.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;

/**
 * 针对 mapper层返参进行特殊处理
 */
@Component
@Aspect
public class MapperReturnDataAspect {
    private static final Logger log = LoggerFactory.getLogger(MapperReturnDataAspect.class);
    //定义pointcut签名
    @Pointcut("execution(* com.taia.yms.mapper.*.*(..)) && @annotation(com.taia.yms.aop.reponse.MapperReturnData)")
    private void pointCut() {
        //方法为空,仅做签名
    }

    //对切点方法进行前置增强,就是在调用切点方法前进行做一些必要的操作,这就成为增强
    @Around("pointCut()")
    public Object getRes(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取被拦截的方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取被拦截的方法
        Method method = signature.getMethod();
        // 获取返回值
        Object returnObj = joinPoint.proceed();
        MapperReturnData annotation = method.getAnnotation(MapperReturnData.class);
        // 查找并获取注解
        try{
            // 读取注解的属性
            Class<? extends MapperReturnDataInterface> operation = annotation.operation();
            MapperReturnDataInterface operationInstance = operation.getDeclaredConstructor().newInstance();
            String methoded = annotation.method();
            Method operationMethod = operation.getDeclaredMethod(methoded, Object.class);
            return operationMethod.invoke(operationInstance,returnObj);
        }catch (Exception e){
            log.error("类[{}]的方法[{}]执行失败,报错:{}",annotation.operation().getName(),annotation.method(),e.getMessage());
            return returnObj;
        }
    }

}

4,编写业务处理实现

java 复制代码
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


public class TechnologyGetDataTypeList implements MapperReturnDataInterface<List<String>>{
    @Override
    public List<String> transferReturnData(Object request) {
        List<String> list = (List<String>) request;
        if(CollectionUtils.isEmpty(list)){
            return new ArrayList<>(1);
        }
        List<String> results = list.stream()
                .map(v -> v.substring(v.indexOf("_")+1))
                .collect(Collectors.toList());
        return results;
    }
}

5,在mapper指定接口方法上使用

java 复制代码
    @MapperReturnData(operation = TechnologyGetDataTypeList.class)
    List<String> getDataTypeList(List<String> columnList);
相关推荐
vipxieliang2 分钟前
PHP Swoole 协程模型详解:协程与线程/进程、调度、常驻内存及与 Go goroutine 的异同
后端·php
lazy H4 分钟前
【计算机网络】第 12 篇:IPv6 详解——地址格式、地址类型与双栈网络
网络·经验分享·后端·学习·计算机网络·408
Thanks_ks6 分钟前
从 0.1+0.2 不等于 0.3 说起:聊聊浮点数精度问题
java·python·数值计算·精度丢失·bigdecimal·浮点数·ieee754
海鸥-w14 分钟前
区域名称同步存储实现笔记
java·笔记
Rain的Java大神之路21 分钟前
LeetCode 21 合并两个有序链表:一道 Easy 题,凭什么刷掉一半候选人?
java·后端·算法
小白的码BUG之路25 分钟前
K8S -- 集群搭建环境基础
java·服务器·kubernetes
w_t_y_y26 分钟前
JWT(5)JWT+spring security
java·后端·spring
wenyq736 分钟前
LeetCode 152. Maximum Product Subarray
java·算法·leetcode
余额瞒着我当琳38 分钟前
C++异常,异常的概念,异常抛出与捕获,RAII 和智能指针的设计思路,C++标准库一些指针的使用
java·开发语言·c++·算法