The Lifecycle of a Spring Bean
Every Spring Bean passes through well-defined stages:
- 1. Instantiation: Spring runs
new MyBean()behind the scenes. - 2. Populate Properties: Spring injects all dependencies into the constructor or fields.
- 3. Post-Construct (@PostConstruct): Spring executes your custom initialization method.
- 4. Bean Ready: The bean is active and serving requests in your application.
- 5. Pre-Destroy (@PreDestroy): When app shuts down, Spring calls clean-up methods (close DB connections, release files).
DatabaseConnectionBean.java
@Component
public class DatabaseConnectionBean {
@PostConstruct
public void init() {
System.out.println("Step 3: Bean initialized! Connecting to DB...");
}
@PreDestroy
public void cleanup() {
System.out.println("Step 5: App stopping! Closing DB connections gracefully...");
}
}