Home > Enterprise >  Sprinng-aop @Around is not working as expected
Sprinng-aop @Around is not working as expected

Time:05-17

I have written a simple AOP to log request and execution time. Everything working fine, but while using the annotation to log the execution time it's not retuning any response though http status code is 200.

Could you please let me know what is the issue ?

Controller:

@LogExecutionTime
@GetMapping("/test")
public String index(){
   return "Hello";
}

Aspect:

@Around("@annotation(LogExecutionTime)")
public void logTime(ProceedingJoinPoint jp) throws Throwable{
  watch.start() // common lang stopwatch
  jp.proceed();
  watch.stop();

 log,info("Execution time "  watch);
}

in log I can see it's showing the execution time but in postman I am not getting the response "hello" if I comment the @LogExecutionTime annotation it's working fine

CodePudding user response:

Aspects of type "around" have the ability to modify the return value. The proceed method returns the value from the original method, which you are silently ignoring, and opting to not return anything (which I believe then defaults the call to returning null). You need to modify your method as follows:

@Around("@annotation(LogExecutionTime)")
public Object logTime(ProceedingJoinPoint jp) throws Throwable{
  watch.start(); // common lang stopwatch
  Object returnValue = jp.proceed();
  watch.stop();

  log.info("Execution time "  watch);

  return returnValue;
}

You might additionally want to place your watch.stop() call in a finally block in case the observed method throws an exception.

  • Related