Bean lifecycle là chuỗi bước Spring tạo → init → dùng → destroy bean.
Các bước chính:
1. Instantiate (new via constructor)
2. Inject dependencies (@Autowired)
3. @PostConstruct method gọi
4. Bean ready — app dùng
5. @PreDestroy method gọi (khi context đóng)
@Component
class ConnectionPool {
private List<Connection> pool;
@PostConstruct
void init() {
pool = createConnections(10); // setup sau DI
}
@PreDestroy
void cleanup() {
pool.forEach(Connection::close); // giải phóng resource
}
}@PostConstruct: khởi tạo sau khi dependencies đã inject (không thể làm trong constructor vì DI chưa chạy xong), load cache từ DB, validate config.
@PreDestroy: giải phóng resource: đóng connection pool, flush buffer, unregister từ external service.
Lựa chọn thay thế: implement InitializingBean / DisposableBean hoặc @Bean(initMethod, destroyMethod) — @PostConstruct được ưu tiên vì không phụ thuộc Spring API.
Bean lifecycle is the sequence of steps Spring takes to create, initialise, use, and destroy a bean.
Key steps:
1. Instantiate (via constructor)
2. Inject dependencies (@Autowired)
3. @PostConstruct method called
4. Bean is ready
5. @PreDestroy method called on shutdown
@Component
class ConnectionPool {
private List<Connection> pool;
@PostConstruct
void init() {
pool = createConnections(10); // setup after DI
}
@PreDestroy
void cleanup() {
pool.forEach(Connection::close);
}
}@PostConstruct: initialise after dependencies are injected, load caches from DB, validate config.
@PreDestroy: release resources: close connection pools, flush buffers, deregister from external services.
Alternatives: implement InitializingBean/DisposableBean or @Bean(initMethod, destroyMethod) — @PostConstruct is preferred since it does not depend on Spring APIs.