The Spring Bean lifecycle starts with instantiation, then dependency injection sets required properties. After that, post-initialization callbacks like @PostConstruct run. Finally, before the bean is removed, pre-destruction callbacks like @PreDestroy execute.
When a bean implements InitializingBean, Spring calls its afterPropertiesSet() method right after dependency injection finishes. This allows the bean to perform any setup needed before use.
If a @PostConstruct method throws an exception, Spring treats it as a failure to create the bean. This causes the application context startup to fail with a BeanCreationException, preventing the app from running.
public class MyBean { public MyBean() { System.out.println("Constructor called"); } @PostConstruct public void init() { System.out.println("PostConstruct called"); } @PreDestroy public void cleanup() { System.out.println("PreDestroy called"); } }
The constructor runs first when the bean is created. Then the @PostConstruct method runs after dependencies are set. Finally, when the app shuts down, the @PreDestroy method runs.
@Component public class MyBean { @PreDestroy public void cleanup() { System.out.println("Cleaning up"); } }
If a bean is created manually with new instead of letting Spring inject it, Spring does not manage its lifecycle. Therefore, lifecycle callbacks like @PreDestroy are never called.