SpringAop通过el表达式动态获取方法入参的值

1.新增工具类

复制代码
import lombok.Data;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.expression.MethodBasedEvaluationContext;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * SpElUtils的增强工具类,相比于SpelUtils,增加了切面对象的上下文。
 * MethodAspectUtils提供的对象,请参考:https://docs.spring.io/spring-framework/reference/integration/cache/annotations.html#cache-spel-context
 * 注意:该方法不支持#beanName语法。
 *
 * 应用场景:
 * <pre>
 *     @Before(value = "@annotation(resource)")
 *     public void checkOperationRight(JoinPoint jp, ProtectResource resource) {
 *         if (!MethodAspectUtils.evaluateWithJoinPointContext(resource.condition(), jp)) {
 *             throw new NoPermissionException("没有权限");
 *         }
 *     }
 *
 *     @ProtectResource(condtion = "#scope.fullDataAccess")
 *     public Department saveOrUpdate(DeptSaveDTO dto, UserDataScope scope) {
 *
 *     }
 * </pre>
 *
 * @see org.springframework.cache.annotation.Cacheable#key()
 * @author zhanghuangbin
 * @date 2024/11/15
 */
public class MethodAspectUtils {


    private static final Map<String, Expression> KEY_CACHE = new ConcurrentHashMap<>(64);

    /**
     *
     * @param el spel表达式,<a href="https://docs.spring.io/spring-framework/reference/integration/cache/annotations.html#cache-spel-context">语法</a>
     *           不支持#beanName语法
     * @param jp
     * @return
     * @param <T>
     */
    public static <T> T evaluateWithJoinPointContext(String el, JoinPoint jp) {
       return evaluateWithJoinPointContext(el, jp, null);
    }

    /**
     *
     * @param el
     * @param jp
     * @param result ProceedingJoinPoint.proceed()的结果
     * @return
     * @param <T>
     */
    public static <T> T evaluateWithJoinPointContext(String el, JoinPoint jp, Object result) {
        Expression expression = KEY_CACHE.computeIfAbsent(el, (key) -> {
            SpelExpressionParser parser = new SpelExpressionParser();
            return parser.parseExpression(key);
        });


        MethodContext context = new MethodContext(jp, result);
        MethodBasedEvaluationContext ctx = new MethodBasedEvaluationContext(context, context.getMethod(), context.getArgs(), new DefaultParameterNameDiscoverer());
        ctx.setVariables(context.getAsVariables());
        return (T) expression.getValue(ctx);
    }


    @Data
    static class MethodContext implements Serializable {

        private final Object[] args;

        private final Object target;

        private final Method method;

        private final String methodName;

        private final Class<?> targetClass;

        private Object result;

        public MethodContext(JoinPoint jp) {
            this(jp, null);
        }

        public MethodContext(JoinPoint jp, Object result) {
            args = jp.getArgs();
            target = jp.getTarget();
            method = ((MethodSignature) jp.getSignature()).getMethod();
            methodName = method.getName();
            targetClass = target.getClass();
            this.result = result;
        }

        public Map<String, Object> getAsVariables() {
            Map<String, Object> map = new HashMap<>();
            map.put("args", args);
            map.put("target", target);
            map.put("method", method);
            map.put("methodName", methodName);
            map.put("targetClass", targetClass);
            map.put("result", result);
            return map;
        }
    }
}

2. 在切面中使用

复制代码
@Aspect
@Slf4j
@Component
public class ToggleDatasourceAspect {

    @Around("@annotation(datasource)")
    public Object selectTargetDatasource(ProceedingJoinPoint joinPoint, ToggleDatasource datasource) throws Throwable {
        String el = datasource.databaseId();
        log.info("ToggleDatasource selectTargetDatasource el={}", el);
        String databaseId = MethodAspectUtils.evaluateWithJoinPointContext(el, joinPoint);
        try {
            DynamicDataSourceContextHolder.push(databaseId);
            return joinPoint.proceed();
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
    }
}
相关推荐
Resean02235 小时前
Spring 源码分析(二)配置类的解析与扫描
java·后端·spring
斯维赤11 小时前
SpringBoot接口调不通排查终极方案
java·后端·spring
雪芽蓝域zzs11 小时前
第 8 节:SpringBoot3 整合 Redis7
spring boot
Flynn Liang13 小时前
Java 虚拟线程别乱用:I/O 密集型服务的线程模型与并发度计算
java·spring boot·性能优化·高并发·线程池·虚拟线程
雪芽蓝域zzs15 小时前
第 3 章:完成 User 完整 CRUD(新增、根据 id 查询、修改、删除、查询全部)
spring boot
CoderYanger15 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第一弹)
java·数据库·spring·面试·java-ee·tomcat·mybatis
她的男孩17 小时前
审批人选了「部门主管」,发起却报 Unknown property:Forge Admin 启动时补齐组织变量
spring boot·低代码·工作流引擎
wno70418 小时前
springboot整合FastDFS
java·spring boot·后端
一起_java1 天前
技术文章-基于Dify-Agent的智能问答系统设计与实现
java·spring boot·后端·agent·dify
Flynn Liang1 天前
I/O 密集型高并发实战:Java 服务 10 维优化,从线程打满到 10 万 QPS
java·spring boot·性能优化·高并发·系统设计·虚拟线程·io密集型