Performance: @PostConstruct and @PreDestroy
These annotations affect the initialization and cleanup phases of Spring beans, impacting application startup and shutdown time.
@PostConstruct
public void init() {
// lightweight setup only
this.cache = new HashMap<>();
// defer heavy tasks to async methods
asyncService.loadDataAsync();
}@PostConstruct
public void init() throws InterruptedException {
// heavy logic like blocking IO or long loops
Thread.sleep(5000);
}| Pattern | Blocking Operations | Startup Delay | Shutdown Delay | Verdict |
|---|---|---|---|---|
| Heavy blocking logic in @PostConstruct/@PreDestroy | Yes | High (seconds) | High (seconds) | [X] Bad |
| Lightweight logic with async offloading | No | Low (milliseconds) | Low (milliseconds) | [OK] Good |
@PostConstruct annotation in a Spring Boot application?@PreDestroy in a Spring Boot bean?public class MyBean {
@PostConstruct
public void init() {
System.out.println("Bean is initialized");
}
@PreDestroy
public void cleanup() {
System.out.println("Bean is about to be destroyed");
}
}public class ResourceBean {
@PostConstruct
public void setup() {
System.out.println("Setup resources");
}
@PreDestroy
public void cleanup() {
System.out.println("Cleanup resources");
}
public void start() {
System.out.println("Start method called");
}
}@PostConstruct and @PreDestroy to achieve this?Pass the test and this pattern moves unknown