0
0
Spring Bootframework~8 mins

@After and @AfterReturning in Spring Boot - Performance & Optimization

Choose your learning style9 modes available
Performance: @After and @AfterReturning
MEDIUM IMPACT
These annotations affect the execution timing of aspect code after method calls, impacting CPU usage and response time.
Running code after a method finishes, only if it returns successfully
Spring Boot
@AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result")
public void afterReturningAdvice(JoinPoint jp, Object result) {
    // runs only after successful return
    lightweightLogging(result);
}
Executes advice only on successful returns, reducing unnecessary CPU usage and improving response time.
📈 Performance Gainavoids extra CPU work on exceptions, improving throughput
Running code after a method finishes, only if it returns successfully
Spring Boot
@After("execution(* com.example.service.*.*(..))")
public void afterAdvice(JoinPoint jp) {
    // runs after method regardless of outcome
    heavyLogging();
}
Runs advice even if the method throws an exception, causing unnecessary CPU work and possible delays.
📉 Performance Costadds CPU overhead on failed method calls, blocking response handling
Performance Comparison
PatternCPU UsageExecution TimingImpact on ResponseVerdict
@After (runs always)High on exceptionsAfter method regardless of outcomeCan delay error handling[X] Bad
@AfterReturning (runs on success)Lower CPU usageOnly after successful returnImproves response speed[OK] Good
Rendering Pipeline
These annotations influence when additional code runs relative to the main method execution, affecting CPU scheduling and response timing.
Method Execution
CPU Scheduling
⚠️ BottleneckUnnecessary execution of advice code after failed methods can delay response processing.
Optimization Tips
1Use @AfterReturning to run advice only on successful method returns.
2Avoid @After if you want to skip advice on exceptions to save CPU.
3Monitor advice execution time to prevent response delays.
Performance Quiz - 3 Questions
Test your performance knowledge
Which annotation runs advice only after a method successfully returns?
A@Before
B@After
C@AfterReturning
D@Around
DevTools: Spring Boot Actuator + JVM Profiler
How to check: Enable actuator endpoints and use a JVM profiler to monitor method execution times and advice overhead.
What to look for: Look for advice execution time spikes after exceptions to identify unnecessary overhead.