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 Throwing Advice

After Throwing advice in Aspect-Oriented Programming (AOP) is executed when a method throws an exception. This kind of advice is useful when you want to execute certain behavior (like logging or notifying) specifically when exceptions occur in your application.

Implementation of After Throwing Advice in Spring Boot:

  • Add Dependencies: Ensure you've added 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:

Create an aspect that contains the After Throwing advice:

package com.example.demo.aspect;

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

@Aspect
@Component
public class ErrorLoggingAspect {

    @AfterThrowing(pointcut = "execution(* com.example.demo.service.*.*(..))", throwing = "ex")
    public void afterThrowingAdvice(JoinPoint joinPoint, Throwable ex) {
        System.out.println("An exception has been thrown in " + joinPoint.getSignature().getName() + " with message: " + ex.getMessage());
    }
}

In this code:

  • @Aspect: Marks the class as an aspect.

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

  • @AfterThrowing: Denotes an after-throwing advice. The pointcut attribute specifies when the advice should run. Here, it'll run when any method within the com.example.demo.service package throws an exception. The throwing attribute binds the thrown exception to the ex parameter of the advice method.

  • Apply the Aspect:

The aspect will be applied wherever the conditions in the pointcut expressions are met. In this case, it'll be applied to methods in the com.example.demo.service package that throw exceptions.

  • Run Your Application:

Now, when you run your Spring Boot application and a method matching the pointcut expression throws an exception, you'll see the log message indicating which method threw the exception and the exception's message.

This After Throwing advice allows you to centralize your exception logging, making it easier to keep track of and manage exceptions across various components of your application.

  1. Spring Boot AOP After Throwing Advice example:

    • After Throwing Advice is executed after a method throws an exception.
    • Example:
      @Aspect
      @Component
      public class AfterThrowingAdviceExample {
      
          @AfterThrowing(
              pointcut = "execution(* com.example.service.MyService.myMethod(..))",
              throwing = "exception")
          public void afterThrowingAdvice(Exception exception) {
              // Code to be executed after an exception is thrown
              System.out.println("AfterThrowing advice executed. Exception: " + exception.getMessage());
          }
      }
      
  2. Handling exceptions with After Throwing advice in Spring Boot AOP:

    • After Throwing advice is used for handling exceptions.
    • Example:
      @Aspect
      @Component
      public class ExceptionHandlingAfterThrowingAdvice {
      
          @AfterThrowing(
              pointcut = "execution(* com.example.service.MyService.myMethod(..))",
              throwing = "exception")
          public void handleException(Exception exception) {
              // Code to handle the thrown exception
              System.out.println("Exception handled: " + exception.getMessage());
          }
      }
      
  3. AspectJ After Throwing advice in Spring Boot:

    • AspectJ-style After Throwing advice in Spring Boot AOP.
    • Example:
      @Aspect
      @Component
      public class AspectJAfterThrowingAdvice {
      
          @AfterThrowing(
              pointcut = "execution(* com.example.service.MyService.myMethod(..))",
              throwing = "exception")
          public void afterThrowingAdvice(Exception exception) {
              // Code to be executed after an exception is thrown
              System.out.println("AfterThrowing advice executed. Exception: " + exception.getMessage());
          }
      }
      
  4. Logging and error handling with After Throwing advice in Spring Boot AOP:

    • After Throwing advice is useful for logging and error handling.
    • Example:
      @Aspect
      @Component
      public class LoggingAndErrorHandlingAfterThrowingAdvice {
      
          @AfterThrowing(
              pointcut = "execution(* com.example.service.MyService.myMethod(..))",
              throwing = "exception")
          public void logAndHandleError(Exception exception) {
              // Log the exception and handle the error
              System.out.println("Error occurred: " + exception.getMessage());
          }
      }
      
  5. Using @AfterThrowing advice with Spring Boot AOP:

    • @AfterThrowing is a specialized form of @After advice.
    • Executed after an exception is thrown during method execution.
    • Example:
      @Aspect
      @Component
      public class AfterThrowingAdviceExample {
      
          @AfterThrowing(
              pointcut = "execution(* com.example.service.MyService.myMethod(..))",
              throwing = "exception")
          public void afterThrowingAdvice(Exception exception) {
              // Code to be executed after an exception is thrown
              System.out.println("AfterThrowing advice executed. Exception: " + exception.getMessage());
          }
      }
      
  6. Ordering of multiple After Throwing 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 AfterThrowingAdviceExample1 {
          // Code
      }
      
      @Aspect
      @Component
      @Order(1)
      public class AfterThrowingAdviceExample2 {
          // Code
      }
      
  7. Exception translation with After Throwing advice in Spring Boot:

    • Translate exceptions using After Throwing advice.
    • Convert one exception type to another.
    • Example:
      @Aspect
      @Component
      public class ExceptionTranslationAfterThrowingAdvice {
      
          @AfterThrowing(
              pointcut = "execution(* com.example.service.MyService.myMethod(..))",
              throwing = "exception")
          public void translateException(Exception exception) throws CustomException {
              // Translate the exception to a custom exception
              throw new CustomException("Translated Exception", exception);
          }
      }