DEV Community

Code Green
Code Green

Posted on • Edited on

4

In Spring Boot, what is the use of @PostConstruct? Explain using Example.

Use of @PostConstruct in Spring Boot

====================================

In Spring Boot, @PostConstruct is used to annotate a method that should be executed after dependency injection is complete and before the bean is put into service.

Example:

Suppose we have a class UserService that requires some initialization logic after its dependencies are injected. We can use @PostConstruct to annotate a method for this purpose.

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

@Service
public class UserService {

    @PostConstruct
    public void init() {
        // Initialization logic, e.g., loading configuration, setting up resources, etc.
        System.out.println("UserService initialized!");
    }

    // Other methods of UserService
}

Enter fullscreen mode Exit fullscreen mode

In this example:

  • The UserService class is annotated with @Service to indicate it as a Spring-managed bean.
  • The init method is annotated with @PostConstruct, ensuring it runs automatically after all dependencies of UserService are injected by Spring.
  • Any initialization logic needed for UserService can be placed within the init method.

Conclusion:

@PostConstruct in Spring Boot provides a convenient way to perform initialization tasks for a bean after its dependencies are injected. It ensures that the initialization logic is executed exactly once before the bean is used, contributing to the robustness and reliability of the application.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more