Loading

Quipoin Menu

Learn • Practice • Grow

spring / Advice in AOP
tutorial

Advice in AOP

Think of a security guard at a mall. The guard can act:
  • Before you enter – check your bag.
  • After you leave – thank you for visiting.
  • Around your entire visit – guide you, monitor you, and handle emergencies.
In AOP, these are called advice – the action taken at a particular joinpoint.

Spring AOP provides five types of advice:

  • @Before – Runs before the method executes.
  • @After – Runs after the method finishes (finally block).
  • @AfterReturning – Runs after method returns successfully.
  • @AfterThrowing – Runs if method throws an exception.
  • @Around – Runs before and after method execution (most powerful).

Here are examples of each:


@Aspect
@Component
public class AllAdviceExample {

@Before("execution(* com.example.service.*.*(..))")
public void beforeAdvice() {
System.out.println("@Before: Method is about to execute");
}

@After("execution(* com.example.service.*.*(..))")
public void afterAdvice() {
System.out.println("@After: Method finished execution");
}

@AfterReturning("execution(* com.example.service.*.*(..))")
public void afterReturningAdvice() {
System.out.println("@AfterReturning: Method returned successfully");
}

@AfterThrowing("execution(* com.example.service.*.*(..))")
public void afterThrowingAdvice() {
System.out.println("@AfterThrowing: Method threw an exception");
}

@Around("execution(* com.example.service.*.*(..))")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("@Around: Before method execution");
Object result = joinPoint.proceed();
System.out.println("@Around: After method execution");
return result;
}
}
Two Minute Drill
  • @Before – runs before method.
  • @After – runs after method (finally).
  • @AfterReturning – runs after successful return.
  • @AfterThrowing – runs after exception.
  • @Around – runs before and after, most flexible.
  • Use @Around for tasks like performance monitoring.

Need more clarification?

Drop us an email at career@quipoinfotech.com