Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Logging methods' return values using an after-returning advice


An after-returning advice executes some extra code after the successful execution of the target method. In this recipe, we will log the return value of the target method.

Getting ready

We will use the aspect class defined in the Creating a Spring AOP aspect class recipe.

How to do it…

Here are the steps for logging the return value of methods using an after-returning advice:

  1. In your aspect class, create an advice method annotated with @AfterReturning. Make it take a JoinPoint object and the return value of the target method as arguments:

    @AfterReturning(pointcut="execution(* com.spring_cookbook.controllers.*.*(..))", returning="returnValue")
    public void logReturnValue(JoinPoint joinPoint, Object returnValue) {
    ...
    }
  2. In that advice method, log the return value preceded by the target method name:

    String className = joinPoint.getSignature().getDeclaringTypeName();
    String methodName = joinPoint.getSignature().getName();
    System.out.println...