0
0
Spring Bootframework~8 mins

@PostConstruct and @PreDestroy in Spring Boot - Performance & Optimization

Choose your learning style9 modes available
Performance: @PostConstruct and @PreDestroy
MEDIUM IMPACT
These annotations affect the initialization and cleanup phases of Spring beans, impacting application startup and shutdown time.
Running initialization logic after bean creation
Spring Boot
@PostConstruct
public void init() {
  // lightweight setup only
  this.cache = new HashMap<>();
  // defer heavy tasks to async methods
  asyncService.loadDataAsync();
}
Lightweight setup runs quickly; heavy tasks run asynchronously without blocking startup.
📈 Performance Gainstartup completes immediately, heavy tasks offloaded, improves app responsiveness
Running initialization logic after bean creation
Spring Boot
@PostConstruct
public void init() throws InterruptedException {
  // heavy logic like blocking IO or long loops
  Thread.sleep(5000);
}
Blocking or heavy operations in @PostConstruct delay application startup and block the main thread.
📉 Performance Costblocks startup for 5 seconds, delaying app readiness
Performance Comparison
PatternBlocking OperationsStartup DelayShutdown DelayVerdict
Heavy blocking logic in @PostConstruct/@PreDestroyYesHigh (seconds)High (seconds)[X] Bad
Lightweight logic with async offloadingNoLow (milliseconds)Low (milliseconds)[OK] Good
Rendering Pipeline
These annotations run methods during bean lifecycle events, affecting the app's startup and shutdown phases but not the browser rendering pipeline.
Application Initialization
Application Shutdown
⚠️ BottleneckBlocking or heavy operations inside these methods can delay startup or shutdown.
Optimization Tips
1Keep @PostConstruct methods lightweight to avoid blocking app startup.
2Avoid blocking calls in @PreDestroy to ensure fast application shutdown.
3Offload heavy or slow tasks to asynchronous processes outside lifecycle methods.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of putting heavy blocking code inside @PostConstruct?
AIt delays application startup and blocks the main thread.
BIt causes layout shifts in the browser.
CIt increases bundle size significantly.
DIt improves application responsiveness.
DevTools: Spring Boot Actuator / Logs
How to check: Enable startup and shutdown logs; measure time taken by @PostConstruct and @PreDestroy methods in logs or use Actuator endpoints.
What to look for: Long delays or blocking calls during startup or shutdown phases indicate performance issues.