Search code examples
javaspringkotlinaopspring-aop

Spring-AOP:@AfterReturning is executed immediately


Hi I am using Spring AOP for logging ,I have two following aspects @Before and @AfterReturning Unfortunately both are printing the same response here the expectation is @Before print method input and @AfterReturning print method output.

 @Before(value ="execution(* com.abc.xyz.service..*(..))")
    fun logBeforeAllMethods(joinPoint: JoinPoint) {
        log.info("Service Request : " + Arrays.toString(joinPoint.args))
    }

    @AfterReturning(value="execution(* com.abc.xyz.service..*(..))")
    fun logAfterAllMethods(joinPoint: JoinPoint) {
        log.info("Service Response : " + Arrays.toString(joinPoint.args))
    }

Solution

  • It is no surprise that both advice methods print the same if you tell them to. In both cases you say you want to print the method arguments. Nowhere are you stating that the result ought to be printed. You do that via the optional returning parameter in the @AfterReturning annotation.

    Maybe you want to check the Spring manual, there is an example for what you want to do (even available in Kotlin!).

    @Aspect
    class AfterReturningExample {
      @AfterReturning(
        pointcut = "com.xyz.myapp.CommonPointcuts.dataAccessOperation()",
        returning = "retVal")
      fun doAccessCheck(retVal: Any) {
          // ...
      }
    }
    

    Of course you can also bind both the joinpoint and return value to method parameters if you need both in your advice.