Spring Framework FAQ: Top Questions
13. What is the purpose of the @PostConstruct and @PreDestroy annotations?
@PostConstruct
and @PreDestroy
are lifecycle annotations used for initialization and cleanup logic in Spring-managed beans.
πΊοΈ Step-by-Step:
@PostConstruct
marks a method to be executed after dependency injection.@PreDestroy
marks a method to be executed before bean destruction.
π₯ Example:
@Component
public class ResourceBean {
@PostConstruct
public void init() {
System.out.println("Initializing resources...");
}
@PreDestroy
public void destroy() {
System.out.println("Cleaning up before shutdown...");
}
}
π Expected Output:
Prints initialization and cleanup messages at appropriate lifecycle phases.
π οΈ Use Cases:
- Opening/closing connections or files.
- Custom bean initialization tasks.