Spring-AOP:@AfterReturning会立即执行

huangapple go评论84阅读模式
英文:

Spring-AOP:@AfterReturning is executed immediately

问题

@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))
}
英文:

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))
    }

答案1

得分: 1

毫不意外的是,这两种建议方法在被调用时打印出相同的内容。在这两种情况下,您表示希望打印方法的 参数。您并没有说明应该打印 结果。您可以通过 @AfterReturning 注解中的可选的 returning 参数来实现这一点。

也许您想要查阅一下 Spring 手册,在那里有一个关于您想要做的事情的示例(甚至有 Kotlin 版本!)。

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

当然,如果您在建议中需要同时绑定连接点和返回值,您也可以将它们都绑定为方法参数。

英文:

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.

huangapple
  • 本文由 发表于 2020年10月1日 06:47:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64146779.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定