Log the return value of a method using spring aop

prabu picture prabu · Aug 27, 2013 · Viewed 24.5k times · Source

I have a method which returns an object. I would like to print that object's value in my log using spring AOP. How can I achieve that?

Please help!

Answer

Shaun Hare picture Shaun Hare · Aug 27, 2013

Using @AfterReturning with a returnValue param.

You could then interogate the object returned This is an example where I do it on everything but get methods in a repository

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