Run initialisation after injection, and cleanup before the context closes.
@Component
class ConnectionPool {
@PostConstruct
void open() { System.out.println("pool opened"); }
@PreDestroy
void close() { System.out.println("pool closed"); }
}
pool opened <- after the constructor AND after injection
... application runs ...
pool closed <- on graceful shutdown only (not on kill -9)
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-08-11