![]() |
VOOZH | about |
In Spring AOP, After Advice is used to execute code after a target method finishes execution. It is defined using the @After annotation. The advice method runs regardless of whether the method executes successfully or throws an exception. This makes it useful for tasks like logging, resource cleanup, or auditing after method execution.
@After("execution(* package_name.class_name.method_name(..))")
public void afterAdviceMethod(JoinPoint joinPoint) {
// code to run after method execution
}
Follow these steps to configure and apply After Advice in a Spring Boot application using AOP.
Open Spring Initializr and provide the following details:
Download the project and extract the ZIP file.
Import the project using: File -> Import -> Existing Maven Project -> Select Project Folder -> Finish.
pom.xml file:
Note: If the jars are not added properly, you may get some errors.
Create package com.after_advice.model and add Student.java class to store student details such as firstName and secondName.
Student class:
Create package com.after_advice.service and add StudentService.java. This class contains the addStudent() method which creates and returns a student object.
StudentService class:
Create package com.after_advice.controller and add StudentController.java. This controller handles GET request /add and calls the StudentService method.
StudentController class:
Create package com.after_advice.aspect and add StudentServiceAspect.java.
StudentServiceAspect class:
Run the project as Spring Boot Application and open the browser.
Example URL:
👁 Image
For a demo, we are hitting URL with fname as Harry and sname as Potter. In this case, the method will be executed normally.
Case 1: Normal Execution
Case 2: Exception Occurs
When we hit URL with fname as Tom, the service method will throw an exception. The After advice will be executed.
As seen in the output, the advice method is called after the service method is executed successfully or any exception is raised.