英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论