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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay