You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中带suspend修饰的Aspect切面未被调用问题求助

解决Spring AOP中Suspend切面方法未触发的问题

带suspend修饰的切面方法未被调用,核心原因是Spring AOP默认的方法签名匹配机制无法识别Kotlin协程编译后的suspend方法(编译后会自动添加Continuation参数,导致方法签名与普通@Around切面方法不一致),同时普通的ProceedingJoinPoint也不支持协程挂起逻辑的处理。以下是具体解决步骤:

1. 替换连接点参数类型

将切面方法中的ProceedingJoinPoint替换为Spring提供的CoroutineProceedingJoinPoint,它专门用于处理协程场景下的连接点,且proceed()方法本身也是suspend修饰的,能正确处理挂起逻辑。

2. 调整切面代码

移除冲突的普通切面方法,修改后的切面类如下:

@Aspect
@Component
class NotBlockingAdvice {

    @Around("@annotation(org.springframework.web.bind.annotation.GetMapping)")
    suspend fun notGettingInvoked(joinPoint: CoroutineProceedingJoinPoint): Any? {
        println("This is now getting called")
        return joinPoint.proceed()
    }
}

3. 确保依赖与版本支持

  • 使用Spring Framework 5.3+或Spring Boot 2.4+,这些版本对Kotlin协程的AOP支持更完善。
  • 若为Spring MVC项目,需引入kotlinx-coroutines-spring依赖,该依赖提供了协程与Spring集成的必要支持。

额外说明

  • 无论目标Controller方法是否为suspend修饰,CoroutineProceedingJoinPoint都能兼容处理,切面的suspend方法都会被触发。
  • 避免在同一个切面中同时存在普通和suspend的同切点切面方法,否则Spring会优先执行普通方法。

内容的提问来源于stack exchange,提问作者Vivek Adhikari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 04:22:14