欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring aop处理返回结果

程序员文章站 2022-05-26 14:18:18
...
/**
 * 处理返回结果
 *
 * @author admin
 */
@Aspect
public class ResultPoint {

    private static Log LOG = LogFactory.getLog(SortPoint.class);

    @AfterReturning(value = "@annotation(注解A) || @annotation(注解B)", returning = "result")
    public void sortDealWith(JoinPoint jp, Object result) {
        if (Objects.nonNull(result)) {
            var baseClass = result.getClass().getSuperclass();
            //AbstractBaseResult.class为返回结果继承父类
            if (baseClass.equals(AbstractBaseResult.class)) {
                var returnResult = (AbstractBaseResult) result;
                if (MapTool.isNotEmpty(returnResult.getDicts())) {
                    if (returnResult.getReturnMap().containsKey("SORT_KEY")) {
                        //在方法里已处理不进行处理
                        return;
                    }
                }
                try {
                    Signature signature = jp.getSignature();
                    MethodSignature methodSignature = (MethodSignature) signature;
                    Method targetMethod = methodSignature.getMethod();
                    Type returnType = targetMethod.getGenericReturnType();
                    if (returnType instanceof ParameterizedType) {
                        // 返回类型是泛型类型
                        var targetType = ((ParameterizedType) returnType)
                                .getActualTypeArguments()[0];
                        if (targetType instanceof Class) {
                            var targetClass = ((Class) targetType);
                            if (targetClass.isPrimitive() || isWrapClass(targetClass)) {
                                //泛型为基础类型或包装类型跳过
                                return;
                            }
                              returnResult.getReturnMap().putAll(处理值方法(targetClass));
                        }
                    }
                } catch (Exception e) {
                    LOG.error("获取排序字段异常",e);
                }
            }
        }
    }

    /**
     * 是否为包装类型
     */
    private boolean isWrapClass(Class clz) {
        try {
            return ((Class) clz.getField("TYPE").get(null)).isPrimitive();
        } catch (Exception e) {
            return false;
        }
    }

 

相关标签: 工具方法