javaspringspring-bootaopspring-aop

Spring AOP @Afterreturning aspect blocks api call


I have an @Afterreturning aspect.

@AfterReturning(value = "@annotation(****)",returning = "returnValue")
    public void auditableUponReturn(final JoinPoint joinPoint, Object returnValue) {
       //takes 500 ms
      }

I have an endpoint which invokes this aspect

@GetMapping("/{id}")
    @AspectInvoker
    public Name getName(){
       //takes 100 ms
    }

when I call this endpoint I am expecting this endpoint to take 100 ms and return back instantly while my aspect related code is in process. But the endpoint doesnot return until aspect related code is complete.

Is this expected? Any way to get around this so that performance of apis is not impacted by aspect related code?


Solution

  • Yes, the behavior you are experiencing is expected. The reason for this is that your registered Aspect operates in the same thread as your endpoint.

    You can utilize @Async (along with @EnableAsync) to execute the Aspect logic in a separate thread. But this approach creates a new thread each time your method is called. It is questionable whether this gives you a significant performance advantage over synchronous execution of the aspect.

    You might find this thread helpful for a more comprehensive understanding: Will an aspect be executed asynchronously if I put @Async method on it?