Discover how to run code after any method finishes without cluttering your main code!
Why @After and @AfterReturning in Spring Boot? - Purpose & Use Cases
Imagine you have many methods in your application, and you want to run some code after each method finishes, like logging or cleaning up resources.
You try to add this code manually inside every method.
Manually adding the same code after every method is boring, error-prone, and makes your code messy.
If you forget to add it somewhere, your app might behave inconsistently.
@After and @AfterReturning let you write that extra code once and have it run automatically after methods finish, keeping your code clean and consistent.
public void someMethod() {
// method logic
System.out.println("Method finished");
}@After("execution(* com.example..*(..))") public void afterAdvice() { System.out.println("Method finished"); }
You can add behavior after methods run without touching their code, making maintenance easier and your app more reliable.
Logging user actions after every service method completes, without adding logging code inside each method.
@After and @AfterReturning run code after methods finish.
They keep your code clean by separating extra tasks from main logic.
This helps maintain consistency and reduces errors.