0
0
SpringbootConceptBeginner · 3 min read

@PostConstruct in Spring: What It Is and How It Works

@PostConstruct is a Spring annotation used to mark a method that should run once immediately after the bean's dependencies are injected. It helps perform initialization tasks right after the bean is created but before it is used.
⚙️

How It Works

Imagine you have a new appliance that needs to be plugged in and set up before you can use it. In Spring, when a bean is created, its dependencies are injected first, like plugging in the appliance. The @PostConstruct method is like the setup instructions you follow right after plugging it in but before turning it on.

This annotation tells Spring to call the marked method once all the bean's dependencies are ready. It runs only once during the bean's lifecycle, ensuring any setup or initialization code runs at the right time, after injection but before the bean is available for use.

💻

Example

This example shows a Spring bean with a @PostConstruct method that initializes a message after dependencies are set.

java
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;

@Component
public class GreetingService {

    private String message;

    public GreetingService() {
        this.message = "";
    }

    @PostConstruct
    public void init() {
        this.message = "Hello, Spring!";
        System.out.println("PostConstruct method called: message initialized.");
    }

    public String getMessage() {
        return message;
    }
}
Output
PostConstruct method called: message initialized.
🎯

When to Use

Use @PostConstruct when you need to run setup code after Spring injects all dependencies into a bean. This is useful for tasks like initializing resources, validating injected values, or starting background threads.

For example, if your bean depends on configuration values or other beans, and you want to prepare some data or connections before the bean is used, @PostConstruct is the right place to do it.

Key Points

  • Runs once: The method marked with @PostConstruct runs only once after bean creation.
  • After injection: It executes after all dependencies are injected.
  • Initialization: Ideal for setup tasks like resource allocation or validation.
  • Method signature: The method must be void, have no arguments, and can throw exceptions.

Key Takeaways

@PostConstruct runs a method once after Spring injects dependencies into a bean.
Use it to perform initialization tasks before the bean is used.
The method must have no parameters and return void.
It helps keep setup code separate from constructors for cleaner design.