javaspringspring-bootspring-webfluxspring-aop

@AfterReturning method not being triggered correctly in Spring webflux Application


I am trying to print response payload after the controller method is executed in the application, but the afterReturning aspect doesn't seem to work correctly.It gets triggered before the actual method is executed. This is a spring webflux application.

 @AfterReturning(value="pointCut()",returning = "respValue")
  public void logResponse(JoinPoint joinPoint, Object respValue) throws Exception {
    .......
    log.info("response :: {}",respValue);
    }

My controller method:

@PostMapping("/test")
public Flux<Test> addCars(ServerWebExchange serverWebExchange) {
    return service.addCars()
            .onErrorResume(ex -> {
                log.info("error ", ex);
                return Mono.error();
            });
}

Solution

  • I was able to resolve this by modifying my Aspect as below:

     @Around(value="pointCut()")
        public void logResponse(ProceedingJoinPoint joinPoint) throws Throwable {
            Flux<Object> resp = joinPoint.proceed();
              resp.doOnNext(returnValue ->{
              log.info("response :: {}",returnValue);
            }).doFinally(signalType -> {
        if (signalType == SignalType.ON_COMPLETE) {
             log.info("completed");
          }
        });
    }