Spring: Bean lifecycle callbacks with @PostConstruct and @PreDestroy

Run initialisation after injection, and cleanup before the context closes.

Code
@Component
class ConnectionPool {

    @PostConstruct
    void open() { System.out.println("pool opened"); }

    @PreDestroy
    void close() { System.out.println("pool closed"); }
}
Output
pool opened      <- after the constructor AND after injection
... application runs ...
pool closed      <- on graceful shutdown only (not on kill -9)
Advertisement

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