我指的是来源文档:
https://docs.spring.io/spring-framework/reference/languages/kotlin/coroutines.html Spring 框架在以下范围内提供对协程的支持: ... 春季AOP
i just want this method to be invoked as Aspect.
@Aspect
@Component
class NotBlockingAdvice {
@Around("@annotation(org.springframework.web.bind.annotation.GetMapping)")
suspend fun notGettingInvoked(joinPoint: ProceedingJoinPoint): Any? {
System.out.println("This is not getting called")
return joinPoint.proceed();
}
@Around("@annotation(org.springframework.web.bind.annotation.GetMapping)")
fun gettingInvoked(joinPoint: ProceedingJoinPoint): Any? {
System.out.println("This is getting called")
return joinPoint.proceed();
}
}
Spring AOP 支持意味着您可以使用方面拦截挂起函数。方面方法本身不应该被暂停,并且这不是计划中的,根据维护者的评论。如果您需要在方面内运行挂起函数,则必须自己定义一个范围,例如,使用像
runBlocking {}
: 这样的协程构建器
@Around("@annotation(org.springframework.web.bind.annotation.GetMapping)")
fun gettingInvoked(joinPoint: ProceedingJoinPoint): Any? {
runBlocking {
suspendingFunction()
}
return joinPoint.proceed();
}
suspend fun suspendingFunction() {
println("Hello from suspending function!")
}
或者,如果您在 Reactive Stack 上使用 Spring Web,则可以使用
mono{}
,如下所示:
@Around("@annotation(org.springframework.web.bind.annotation.GetMapping)")
fun alsoGettingInvoked(joinPoint: ProceedingJoinPoint): Any? = mono {
suspendingFunction()
}.then(joinPoint.proceed() as Mono<*>)
suspend fun suspendingFunction() {
println("Hello from suspending function!")
}