当前位置: 首页 > news >正文

spring代理和切面

今天在deepseek上偶然问了这个问题,给出的描述很清楚,抄下来。

拦截器链执行核心

public class ReflectiveMethodInvocation implements MethodInvocation {private final Object target;private final Method method;private final Object[] args;private final List<MethodInterceptor> interceptors;// 关键:当前拦截器索引,记录执行位置private int currentInterceptorIndex = -1;public ReflectiveMethodInvocation(Object target, Method method, Object[] args, List<MethodInterceptor> interceptors) {this.target = target;this.method = method;this.args = args;this.interceptors = interceptors;}@Overridepublic Object proceed() throws Throwable {// 所有拦截器都执行完毕,执行原始目标方法if (currentInterceptorIndex == interceptors.size() - 1) {return method.invoke(target, args);}// 获取下一个拦截器并执行MethodInterceptor interceptor = interceptors.get(++currentInterceptorIndex);return interceptor.invoke(this); // 关键:递归调用链
    }
}

里面的invoke代码不难,类似这样:

    @Overridepublic Object invoke(MethodInvocation invocation) throws Throwable {// 先执行前置逻辑
        beforeAdvice.run();// 继续执行链return invocation.proceed();}

所以proceed差不多可以简化成这样:

    @Overridepublic Object proceed() throws Throwable {// 所有拦截器都执行完毕,执行原始目标方法if (currentInterceptorIndex == interceptors.size() - 1) {return method.invoke(target, args);}// 获取下一个拦截器并执行MethodInterceptor interceptor = interceptors.get(++currentInterceptorIndex);return proceed();}

spring把controller里我们实现的method用一个结构体(class)描述出来,调用的method名字,参数,包括外面用aspect做的切面都塞到结构体里。叫做ReflectiveMethodInvocation。按我的习惯就叫execution。proceed()是一个递归函数,它总是执行下一个切面,除非没有切面了,再执行真正的用户方法。

注意method本体的调用是在else里的,一个切面如果进入另一个切面,它就不执行method了。所以只有咀内层(最末序)的切面有调用method的机会,如果它也没调用,那这个controller的方法就被绕过了。

没接触spring的时候,猜测切面应该就是钩子吧,其实是比钩子高级的钩子,重要的是它把方法调用描述成数据结构,然后再“手动”调用,这样对方法所处的执行点位的执行流和执行内容能全权控制。

http://www.gsyq.cn/news/40341.html

相关文章:

  • P7371 [COCI 2018/2019 #4] Kisik 题解
  • C# 状态机
  • [引]Regenerate the SAS key used in HTTP trigger flows
  • 11月4号
  • [UNIX]A Quarter Century of Unix by Peter H. Salus
  • 2025 年 11 月新风系统厂家推荐排行榜,电竞网咖酒店棋牌室KTV洗浴饭店商场办公室别墅大宅学校诊所中医馆会所美容院,商用家用极寒地区全热交换新风系统公司推荐
  • 2025 年 11 月新风系统厂家推荐排行榜,电竞网咖酒店棋牌室KTV洗浴饭店商场办公室别墅大宅学校诊所中医馆会所美容院,商用家用极寒地区全热交换系统公司精选
  • 2025 年 11 月新风系统厂家推荐排行榜,电竞网咖酒店棋牌室KTV洗浴饭店商场办公室别墅大宅学校诊所中医馆会所美容院,商用家用全热交换极寒地区适用
  • WPF的更新通知
  • 【电子工程师の设备】用于拆焊PCB的热风枪的品牌
  • 怎么设计一个好的Selenium/Appium 自动化框架? 需要考虑哪些问题
  • AIChatManager 应用功能总结
  • 结构体对齐
  • [OLAP] 技术选型对比:Clickhouse vs Doris
  • 计算天数
  • React 中 useCallback 的基本使用和原理解析
  • SpringCloud和K8s实现的微服务各有什么优缺点
  • 2025.11.4总结
  • 2025 年 11 月 EVA 厂家推荐排行榜,eva塑料,eva板材,eva卷材,eva发泡材料,eva橡塑制品公司推荐
  • 20251104 正睿
  • swagger-typescript-api
  • 2025 年 11 月电线电缆厂家推荐排行榜,国标电线电缆,中缆电线电缆,工程电线电缆,环保电线电缆,家用电线电缆,工业电线电缆,光伏电线电缆,耐火电线电缆公司推荐
  • HAL库DMA框架
  • 2025 年 11 月电线电缆厂家推荐排行榜,电力电缆,控制电缆,通信电缆,阻燃电缆,高压电缆公司推荐
  • 2025 年 11 月回信器厂家推荐排行榜,隔爆回信器,阀门回信器,防爆回信器,限位开关回信器,气动阀回信器,气动回信器公司推荐
  • 数据分析流程
  • 2025 年 11 月锅炉厂家推荐排行榜,有机热载体锅炉,导热油锅炉,生物质锅炉,蒸汽锅炉,燃天然气锅炉,热水锅炉公司推荐
  • 9.22 未完成的情感投射
  • 2025 年 11 月电磁阀厂家推荐排行榜,高压电磁阀,防爆电磁阀,比例电磁阀,汽车电磁阀,ABS电磁阀,ESP电磁阀,车用ESC电磁阀公司推荐
  • 请求库的封装