0
0
Spring Bootframework~3 mins

Why @PostConstruct and @PreDestroy in Spring Boot? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app could prepare and clean up itself perfectly every time, without you lifting a finger?

The Scenario

Imagine you have a Java class that needs to open a database connection when it starts and close it when it stops. You write code to do this manually in many places, like constructors and shutdown hooks.

The Problem

Manually managing setup and cleanup is tricky. You might forget to close resources, causing memory leaks. It's hard to keep track of when to run this code, especially as your app grows.

The Solution

@PostConstruct and @PreDestroy let you mark methods to run automatically right after creation and just before destruction of a Spring bean. This keeps setup and cleanup neat and reliable.

Before vs After
Before
public class MyService {
  public MyService() {
    openConnection();
  }
  public void close() {
    closeConnection();
  }
}
After
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class MyService {
  @PostConstruct
  public void init() {
    openConnection();
  }
  @PreDestroy
  public void cleanup() {
    closeConnection();
  }
}
What It Enables

This makes your app safer and easier to maintain by automating resource setup and cleanup at the right times.

Real Life Example

Think of a coffee machine that automatically heats water when turned on and cleans itself before turning off. @PostConstruct and @PreDestroy do the same for your app's resources.

Key Takeaways

Manual resource management is error-prone and hard to track.

@PostConstruct runs setup code after bean creation.

@PreDestroy runs cleanup code before bean destruction.