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!
After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return). Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice.
Join Point: A join point is a specific point in the application such as method execution, exception handling, changing object variable values, etc. In Spring AOP a join point is always the execution of a method. Advice: Advices are actions taken for a particular join point.
In Spring AOP, a join point always represents a method execution. A pointcut is a predicate that matches the join points, and the pointcut expression language is a way of describing pointcuts programmatically.
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);
}
}
In our case, majority of the time we return entity classes of spring modal, so we overridden the toString method of all entity classes with required minimal information and printed as below
@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.");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With