Performance: @After and @AfterReturning
These annotations affect the execution timing of aspect code after method calls, impacting CPU usage and response time.
@AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result") public void afterReturningAdvice(JoinPoint jp, Object result) { // runs only after successful return lightweightLogging(result); }
@After("execution(* com.example.service.*.*(..))")
public void afterAdvice(JoinPoint jp) {
// runs after method regardless of outcome
heavyLogging();
}| Pattern | CPU Usage | Execution Timing | Impact on Response | Verdict |
|---|---|---|---|---|
| @After (runs always) | High on exceptions | After method regardless of outcome | Can delay error handling | [X] Bad |
| @AfterReturning (runs on success) | Lower CPU usage | Only after successful return | Improves response speed | [OK] Good |
@After and @AfterReturning in Spring AOP?@After behavior@After advice runs after a method finishes, whether it returns normally or throws an exception.@AfterReturning behavior@AfterReturning advice runs only if the method completes successfully without throwing exceptions.@After runs after method completion regardless of outcome; @AfterReturning runs only after successful return. -> Option A@After = always after, @AfterReturning = after success [OK]@AfterReturning advice method in Spring AOP?@AfterReturning annotation requires a pointcut expression and optionally a returning attribute to capture the returned value.returning to receive the returned value.someMethod() throws an exception?
@After("execution(* com.example.Service.someMethod(..))")
public void afterAdvice() {
System.out.println("After advice executed");
}
@AfterReturning(pointcut = "execution(* com.example.Service.someMethod(..))", returning = "result")
public void afterReturningAdvice(Object result) {
System.out.println("AfterReturning advice executed with: " + result);
}@After advice behavior on exception@After advice runs after method finishes regardless of success or exception, so it will execute and print its message.@AfterReturning advice behavior on exception@AfterReturning advice runs only if the method returns successfully, so it will NOT run if an exception is thrown.@AfterReturning(pointcut = "execution(* com.example.Service.process(..))", returning = "retVal")
public void afterReturn() {
System.out.println("Returned value: " + retVal);
}returning = "retVal" attribute requires the advice method to have a parameter named retVal to receive the returned value.retVal, causing a compile error.@AfterReturning advice runs only after successful method return, so it is suitable to log the returned value.@After advice runs after method completion whether success or exception, so it is suitable to log a message always.@AfterReturning to log the returned value and @After to log after method completion. -> Option BPass the test and this pattern moves unknown