使用spring aop记录方法的返回值

pra*_*abu 8 spring-aop

我有一个返回对象的方法.我想使用spring AOP在我的日志中打印该对象的值.我怎样才能做到这一点?

请帮忙!

Sha*_*are 13

将@AfterReturning与returnValue参数一起使用.

然后你可以插入返回的对象.这是一个例子,我在所有内容上执行它,但在存储库中获取方法

@AfterReturning(value = "@target(org.springframework.stereotype.Repository) && !execution(* get*(..))", returning = "returnValue")
public void loggingRepositoryMethods(JoinPoint joinPoint, Object returnValue) {
    String classMethod = this.getClassMethod(joinPoint);



     if(returnValue !=null)
     {
       //test type of object get properties (could use reflection)
       log it out
     }
     else
     {
         //do logging here probably passing in (joinPoint, classMethod);
     }
}
Run Code Online (Sandbox Code Playgroud)


Jaj*_*rla 5

在我们的例子中,大多数时候我们返回spring modal的实体类,所以我们用所需的最小信息覆盖所有实体类的toString方法,并打印如下

@AfterReturning(pointcut = "within(@org.springframework.stereotype.Service *)", returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
    logger.info(" ###### Returning for class : {} ; Method : {} ", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName());
    if (result != null) {
        logger.info(" ###### with value : {}", result.toString());
    } else{
        logger.info(" ###### with null as return value.");
    }
}
Run Code Online (Sandbox Code Playgroud)