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

RMAG news

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
}

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.

Please follow and like us:
Pin Share