Sobes.tech
Junior — Middle

What is the role and purpose of the @PostConstruct annotation in Spring, and in what situations is it used?

sobes.tech AI

Answer from AI

The @PostConstruct annotation in Spring is used to designate a method that should be executed after Spring creates and initializes the bean, but before the bean is available for use.

This is convenient for performing additional initialization, such as resource setup, state verification, or starting logic that depends on already injected dependencies.

Example of usage:

@Component
public class MyBean {

    @PostConstruct
    public void init() {
        // initialization code
        System.out.println("Bean initialized");
    }
}

@PostConstruct is used when you need to ensure that the method is called once after the bean is fully configured, without needing to call it manually.