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

The Before advice in Aspect-Oriented Programming (AOP) is executed before the advised method. It's mainly used when we need to execute a certain piece of code before the actual method execution. For instance, it's helpful for tasks like logging, security checks, or initializing resources.

Let's implement the Before advice in a Spring Boot application:

Implementation of Before Advice in Spring Boot:

  • Add Dependencies: First and foremost, ensure that 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 Before advice.

package com.example.demo.aspect;

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

@Aspect
@Component
public class LoggingAspect {

    @Before("execution(* com.example.demo.service.*.*(..))")
    public void beforeAdvice(JoinPoint joinPoint) {
        System.out.println("Executing before method: " + joinPoint.getSignature().getName());
    }
}

In the code above:

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

  • @Component: Registers the aspect as a Spring bean to ensure it gets picked up during the component scanning.

  • @Before: This annotation denotes a before advice. The expression within execution() specifies when the advice should run. In this example, it will run before any method in any class within the com.example.demo.service package.

  • Apply the Aspect:

Once defined, the aspect will be automatically applied wherever the conditions in the pointcut expressions are met. In our case, it will be applied to any method within the com.example.demo.service package.

  • Run Your Application:

Start your Spring Boot application. Now, every time you call a method that matches the pointcut expression, you'll see the log message before the actual method's execution.

The Before advice is very useful when we need to enforce certain behaviors, like logging or security checks, before the main business logic of a method is executed. It allows us to keep our main business logic clean and separated from these cross-cutting concerns.

  1. Spring Boot AOP Before Advice example:

    • Before Advice is executed before a method is invoked.
    • Example:
      @Aspect
      @Component
      public class BeforeAdviceExample {
      
          @Before("execution(* com.example.service.MyService.myMethod(..))")
          public void beforeAdvice() {
              // Code to be executed before the method
              System.out.println("Before advice executed");
          }
      }
      
  2. AspectJ Before advice in Spring Boot:

    • AspectJ-style Before advice in Spring Boot AOP.
    • Example:
      @Aspect
      @Component
      public class AspectJBeforeAdvice {
      
          @Before("execution(* com.example.service.MyService.myMethod(..))")
          public void beforeAdvice() {
              // Code to be executed before the method
              System.out.println("Before advice executed");
          }
      }
      
  3. Method interception and pre-processing with Before advice in Spring Boot:

    • Before advice intercepts and pre-processes method calls.
    • Example:
      @Aspect
      @Component
      public class PreProcessingBeforeAdvice {
      
          @Before("execution(* com.example.service.MyService.myMethod(..))")
          public void preProcess() {
              // Code for pre-processing before method execution
              System.out.println("Pre-processing before method execution");
          }
      }
      
  4. Using @Before advice with Spring Boot AOP:

    • @Before is a declarative way of defining Before advice.
    • Executed before the method specified in the pointcut.
    • Example:
      @Aspect
      @Component
      public class BeforeAdviceExample {
      
          @Before("execution(* com.example.service.MyService.myMethod(..))")
          public void beforeAdvice() {
              // Code to be executed before the method
              System.out.println("Before advice executed");
          }
      }
      
  5. Ordering of multiple Before 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 BeforeAdviceExample1 {
          // Code
      }
      
      @Aspect
      @Component
      @Order(1)
      public class BeforeAdviceExample2 {
          // Code
      }
      
  6. Conditional Before Advice execution in Spring Boot:

    • Use @Before with @Pointcut to conditionally execute advice.
    • Example:
      @Aspect
      @Component
      public class ConditionalBeforeAdviceExample {
      
          @Pointcut("execution(* com.example.service.MyService.myMethod(..))")
          public void myMethodPointcut() {
          }
      
          @Before("myMethodPointcut() && args(param)")
          public void beforeAdvice(String param) {
              // Code to be executed before the method
              System.out.println("Before advice executed. Param: " + param);
          }
      }
      
  7. Combining Before advice with other advices in Spring Boot AOP:

    • Combine @Before with other advices 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");
          }
      
          @After("execution(* com.example.service.MyService.myMethod(..))")
          public void afterAdvice() {
              // Code to be executed after the method
              System.out.println("After advice executed");
          }
      }
      
  8. Aspect-oriented logging with Before advice in Spring Boot:

    • Use Before advice for aspect-oriented logging.
    • Example:
      @Aspect
      @Component
      public class LoggingBeforeAdvice {
      
          @Before("execution(* com.example.service.*.*(..))")
          public void logBeforeMethodExecution() {
              // Logging before any method in the specified package
              System.out.println("Logging before method execution");
          }
      }