VOOZH about

URL: https://www.geeksforgeeks.org/java/spring-boot-aop-before-advice/

⇱ Spring Boot - AOP Before Advice - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Spring Boot - AOP Before Advice

Last Updated : 13 Mar, 2026

In Spring AOP Before Advice is used to execute some code before a target method runs. It is defined using the @Before annotation and is commonly used for tasks like logging, validation, or security checks. This helps keep cross-cutting concerns separate from the main business logic.

  • @Before advice runs before the execution of a target method (join point).
  • It is mainly used for logging, validation, or authentication checks.
  • If an exception occurs in the advice method, the target method will not execute.

Syntax:

@Aspect
public class BeforeExample {
@Before("execution(* com.xyz.dao.*.*(..))")
public void doAccessCheck() {
// ...
}
}

Steps to Implement Before Advice in Spring Boot

Let’s understand the steps required to implement @Before advice in a Spring Boot application, which executes before the target method runs.

Step 1: Create a Spring Boot Project

Open Spring Initializr and provide the following details:

  • Group: com.beforeadvice
  • Artifact: aop-before-advice-example
  • Dependencies: Spring Web

Download the project and extract the ZIP file and Import the Project into IDE

πŸ‘ Image

Step 2: Add Spring AOP Dependency

Add the following dependency in pom.xml:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

Step 3: Create Model Class

Create package com.beforeadvice.model and add Student.java class to store student details (firstName and secondName).

Student class

Step 4: Create Service Class

Create package com.beforeadvice.service and add StudentService.java. This class contains the method addStudent() which creates and returns a student object.

StudentService class:

Step 5: Create Controller Class

Create package com.beforeadvice.controller and add StudentController.java. This controller handles GET request /add and calls the StudentService method.

StudentController class:

Step 6: Create Aspect Class

Create package com.beforeadvice.aspect and add StudentServiceAspect.java.

  • Define a Pointcut to target service methods.
  • Add @Before advice to run before the service method execution.

StudentServiceAspect class

Step 7: Run the Application

Run the project as Spring Boot Application and open the browser.

πŸ‘ Image
πŸ‘ Image

Output Explanation

  1. @Before Advice runs first and logs the method details and student names.
  2. StudentService.addStudent() method executes and creates the student object.
  3. The controller returns the student details as the response.
Comment