Book Image


Book Image


Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
About the Author
About the Reviewers

Using an after advice to clean up resources

An after advice executes some extra code after the execution of the target method, even if an exception is thrown during its execution. Use this advice to clean up resources by removing a temporary file or closing a database connection. In this recipe, we will just log the target method name.

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 using an after advice:

  1. In your aspect class, create an advice method annotated with @After. Make it take JoinPoint as an argument:

    @After("execution(* com.spring_cookbook.controllers.*.*(..))")
    public void cleanUp(JoinPoint joinPoint) {
  2. In that advice method, log the target method name:

    String className = joinPoint.getSignature().getDeclaringTypeName();
    String methodName = joinPoint.getSignature().getName();
    System.out.println("-----" + className + "." + methodName + "() -----");
  3. Test the advice using two controller methods...