Loading

Quipoin Menu

Learn • Practice • Grow

spring / Advice in AOP
interview

Q1. What is Before advice and how do you use it?
Before advice runs before the method execution. It is useful for tasks like authentication checks or logging. Example using @Before:
@Before("execution(* com.example.service.*.*(..))") public void logBefore(JoinPoint joinPoint) { System.out.println("Before: " + joinPoint.getSignature()); }

Q2. What is After returning advice?
After returning advice runs after a method returns successfully. It can access the return value. Example:
@AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result") public void logAfterReturning(JoinPoint joinPoint, Object result) { System.out.println("Returned: " + result); }

Q3. What is After throwing advice?
After throwing advice runs if a method exits by throwing an exception. It can be used for logging errors or sending alerts. Example:
@AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))", throwing = "error") public void logAfterThrowing(JoinPoint joinPoint, Throwable error) { System.out.println("Exception: " + error); }

Q4. What is Around advice?
Around advice surrounds the method invocation, allowing you to perform actions before and after the method, and even control whether the method executes. It uses ProceedingJoinPoint. Example:
@Around("execution(* com.example.service.*.*(..))") public Object around(ProceedingJoinPoint pjp) throws Throwable { System.out.println("Before"); Object result = pjp.proceed(); System.out.println("After"); return result; }

Q5. Can you have multiple advice on the same joinpoint? How is order determined?
Yes, multiple advice can apply. Order is determined by precedence: if advice are from different aspects, you can implement Ordered or use @Order annotation. For same aspect, order is as per declaration (not guaranteed). You can control order explicitly.