![]() |
VOOZH | about |
In Spring AOP, After Throwing Advice is used to execute code when a method throws an exception. It is defined using the @AfterThrowing annotation. This advice is helpful for handling errors, logging exceptions, or performing cleanup operations when something goes wrong during method execution.
Syntax:
@Aspect
public class AfterThrowingExample {
@AfterThrowing("execution(* com.xyz.dao.*.*(..))")
public void doRecoveryActions() {
}
}
Letβs understand the steps required to implement @AfterThrowing advice in Spring AOP, which executes when a target method throws an exception.
Open Spring Initializr and provide the following details:
Download the project and extract the ZIP file.
π ImageCreate package com.afterthrowing.dao and add MockDAO.java.
Create package com.afterthrowing.controller and add DefaultWebController.java.
After that, we will add the index.html page under resources.templates package.
We basically access that model attribute that was passed by the DefaultWebController, as a list was passed on, we just iterate over each entry and print it out.
Create package com.afterthrowing.aspect and add LoggingAspect.java.
Run the project using:
mvn spring-boot:run
Open the browser:
http://localhost:8080/