Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

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:

  1. @PostConstruct marks a method to be executed after dependency injection.
  2. @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.