Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

Spring Boot - AOP After Returning Advice

After Returning advice in Aspect-Oriented Programming (AOP) is executed after a method completes its execution without throwing any exceptions. It allows us to capture the result returned by the advised method and add additional behavior after the method successfully returns.

Implementation of After Returning Advice in Spring Boot:

  • Add Dependencies: First, ensure you've included the necessary dependencies for Spring AOP in your pom.xml:
<!-- Spring Boot Starter AOP -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  • Define an Aspect:

You'll need to create an aspect that contains the After Returning advice.

package com.example.demo.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

    @AfterReturning(pointcut = "execution(* com.example.demo.service.*.*(..))", returning = "result")
    public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
        System.out.println("After method:" + joinPoint.getSignature());
        System.out.println("Returned value: " + result);
    }
}

In the above code:

  • @Aspect: This annotation marks the class as an aspect.

  • @Component: Registers the aspect as a Spring bean.

  • @AfterReturning: This annotation denotes an after-returning advice. The pointcut attribute contains an expression specifying when the advice should run. In this case, it will run after executing any method in any class within the com.example.demo.service package. The returning attribute specifies a name to be used in the advice method to capture the returned value.

  • Apply the Aspect:

The aspect will be applied wherever the conditions in the pointcut expressions are met. In the example provided, it will be applied after executing any method within the com.example.demo.service package and after the method has returned a value.

  • Run Your Application:

When you run your Spring Boot application and call a method that matches the pointcut expression, after the method successfully returns a result, you'll see the log message with the method signature and the returned value.

The After Returning advice is especially useful when you want to take action based on the result of a method, like logging, transforming the result, or applying business rules after a method has completed its core functionality.

  1. Spring Boot AOP After Returning Advice example:

    • After Returning Advice is executed after a method successfully returns.
    • Example:
      @Aspect
      @Component
      public class AfterReturningAdviceExample {
      
          @AfterReturning(
              pointcut = "execution(* com.example.service.MyService.myMethod(..))",
              returning = "result")
          public void afterReturningAdvice(Object result) {
              // Code to be executed after the method returns
              System.out.println("AfterReturning advice executed. Result: " + result);
          }
      }
      
  2. Logging with After Returning advice in Spring Boot AOP:

    • Use After Returning advice for logging after successful method execution.
    • Example:
      @Aspect
      @Component
      public class LoggingAfterReturningAdvice {
      
          @AfterReturning(
              pointcut = "execution(* com.example.service.MyService.logAndReturn(..))",
              returning = "result")
          public void logAfterReturning(String result) {
              // Logging after successful method execution
              System.out.println("Method returned: " + result);
          }
      }
      
  3. AspectJ AfterReturning advice in Spring Boot:

    • AspectJ-style AfterReturning advice in Spring Boot AOP.
    • Example:
      @Aspect
      @Component
      public class AspectJAfterReturningAdvice {
      
          @AfterReturning(
              pointcut = "execution(* com.example.service.MyService.myMethod(..))",
              returning = "result")
          public void afterReturningAdvice(Object result) {
              // Code to be executed after the method returns
              System.out.println("AfterReturning advice executed. Result: " + result);
          }
      }
      
  4. Using @AfterReturning advice with Spring Boot AOP:

    • @AfterReturning is a specialized form of @After advice.
    • Executed after successful method execution.
    • Example:
      @Aspect
      @Component
      public class AfterReturningAdviceExample {
      
          @AfterReturning(
              pointcut = "execution(* com.example.service.MyService.myMethod(..))",
              returning = "result")
          public void afterReturningAdvice(Object result) {
              // Code to be executed after the method returns
              System.out.println("AfterReturning advice executed. Result: " + result);
          }
      }
      
  5. Handling return values with After Returning advice in Spring Boot:

    • After Returning advice allows access to the method's return value.
    • Example:
      @Aspect
      @Component
      public class ReturnHandlingAfterReturningAdvice {
      
          @AfterReturning(
              pointcut = "execution(* com.example.service.MyService.myMethod(..))",
              returning = "result")
          public void handleReturnValue(String result) {
              // Code to handle the return value
              System.out.println("Handling return value: " + result);
          }
      }
      
  6. Ordering of multiple After Returning Advice in Spring Boot AOP:

    • Use @Order annotation to specify the order of execution.
    • Higher value means lower priority.
    • Example:
      @Aspect
      @Component
      @Order(2)
      public class AfterReturningAdviceExample1 {
          // Code
      }
      
      @Aspect
      @Component
      @Order(1)
      public class AfterReturningAdviceExample2 {
          // Code
      }
      
  7. Conditional After Returning Advice execution in Spring Boot:

    • Use @AfterReturning with @Pointcut to conditionally execute advice.
    • Example:
      @Aspect
      @Component
      public class ConditionalAfterReturningAdviceExample {
      
          @Pointcut("execution(* com.example.service.MyService.myMethod(..))")
          public void myMethodPointcut() {
          }
      
          @AfterReturning(
              pointcut = "myMethodPointcut() && args(param)",
              returning = "result")
          public void afterReturningAdvice(String param, Object result) {
              // Code to be executed after the method returns
              System.out.println("AfterReturning advice executed. Param: " + param + ", Result: " + result);
          }
      }
      
  8. Combining Before advice with After Returning advice in Spring Boot AOP:

    • Combine @Before and @AfterReturning advice for comprehensive behavior.
    • Example:
      @Aspect
      @Component
      public class CombinedAdviceExample {
      
          @Before("execution(* com.example.service.MyService.myMethod(..))")
          public void beforeAdvice() {
              // Code to be executed before the method
              System.out.println("Before advice executed");
          }
      
          @AfterReturning(
              pointcut = "execution(* com.example.service.MyService.myMethod(..))",
              returning = "result")
          public void afterReturningAdvice(Object result) {
              // Code to be executed after the method returns
              System.out.println("AfterReturning advice executed. Result: " + result);
          }
      }