Master Spring Bean Lifecycle: Init & Destroy Hooks with @PostConstruct & @PreDestroy
This guide explains the Spring bean lifecycle, focusing on the key initialization and destruction hook methods using @PostConstruct and @PreDestroy annotations, with code examples, usage tips, and important considerations for prototype-scoped beans.
When studying Spring source code, especially the IOC part, you may have learned about bean lifecycle but find it hard to remember the whole process. You only need to grasp the key points. The bean lifecycle is illustrated in the diagram below.
The main business extension hooks to focus on are:
During bean initialization, you can add custom code:
Invoke custom business logic methods
Set resources such as databases, sockets, files, etc.
During bean destruction, you can add custom code:
Invoke custom business logic methods
Clean up resources (databases, sockets, files, etc.)
1. Initialization Hook
Simply annotate a method with @PostConstruct. The method will be called during bean initialization, for example:
@Component
public class CricketCoach implements Coach {
public CricketCoach() {
System.out.println("In constructor: " + getClass().getSimpleName());
}
@PostConstruct
public void doMyStartupStuff() {
System.out.println("In myInit method: " + getClass().getSimpleName());
}
}After restarting the application, you can see the printed output in the console (make sure to remove any global lazy‑loading configuration previously added in the configuration file).
2. Destruction Hook
Similarly, annotate a method with @PreDestroy. The method will be called before bean destruction, for example:
@Component
public class CricketCoach implements Coach {
public CricketCoach() {
System.out.println("In constructor: " + getClass().getSimpleName());
}
@PostConstruct
public void doMyStartupStuff() {
System.out.println("In myInit method: " + getClass().getSimpleName());
}
@PreDestroy
public void doMyCleanupStuff() {
System.out.println("In myDestroy method: " + getClass().getSimpleName());
}
}When the service stops, the console will show the destruction messages.
Tip Prototype bean and its destruction lifecycle require attention: the prototype scoped bean’s Spring container does not invoke the destroy hook, although the initialization hook still runs. Unlike other scopes, Spring does not manage the full lifecycle of a prototype bean after the container has instantiated, configured, and assembled it; the client is responsible for its cleanup.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
