![]() |
VOOZH | about |
Spring AOP (Aspect-Oriented Programming) helps separate cross-cutting concerns like logging, security, and transaction management from the main business logic of an application. It allows developers to execute additional code at specific points during method execution.
Letβs discuss some commonly used Spring AOP advice annotations that define when the aspect code should be executed during method execution.
@Before advice is used when you want to run some code before a specific method executes like a pre-processing step. @Before advice runs before the execution of a method. It is mainly used for validation or logging before the actual method runs.
Example:
@Before("execution(* com.example.service.*.*(..))")
public void beforeMethod() {
System.out.println("Method is about to execute");
}
@After advice runs after the method execution, whether the method completes successfully or throws an exception.
Example:
@After("execution(* com.example.service.*.*(..))")
public void afterMethod() {
System.out.println("Method execution completed");
}
@Around is an advice type that allows you to run code both before and after the actual method execution.@Around advice runs both before and after the method execution and can control the execution of the method.
Example:
@Around("execution(* com.example.service.*.*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Before method");
Object result = joinPoint.proceed();
System.out.println("After method");
return result;
}
@AfterReturning advice runs only when the method executes successfully and returns a result.
Example:
@AfterReturning(pointcut="execution(* com.example.service.*.*(..))", returning="result")
public void afterReturningMethod(Object result) {
System.out.println("Method returned: " + result);
}
@AfterThrowing will be executed whenever there is an exception in the code. We need to handle that by putting try-catch blocks and always it is a good practice to handle exceptions.
Example:
@AfterThrowing(pointcut="execution(* com.example.service.*.*(..))", throwing="ex")
public void afterThrowingMethod(Exception ex) {
System.out.println("Exception occurred: " + ex.getMessage());
}
Create a Spring Boot project using Spring Initializer with these details:
pom.xml
Create the main Spring Boot application file.DifferentAdviceExampleApplication.java
DifferentAdviceExampleApplication.java
Create DifferentAspect.java and add AOP advice annotations:
This class contains logging and monitoring logic for the service methods.
DifferentAspect.java
Create GeneralService.java which contains methods on which AOP advice will run.
GeneralService.java
Program execution and output:
Output:
Explanation:
Let us see when an exception throws for getBalance method by just passing accountnumber to null
Explanation: