101. @PostConstruct.
- @PostConstruct is a Springboot annotation that is applied to a method.
- The method annotated with this is only triggered once, and is triggered in the bean life-cycle after the dependency injections.
- The life-cycle of a Spring Bean goes like this: Constructor of the class is called --> Dependencies are injected --> @PostConstruct method is called.
When do we use this?
- Initialization Logic: When you need to perform some custom initialization after all dependencies have been injected.
- Resource Setup: When you need to set up resources or connections that the bean will use during its lifetime.
- Configuration Validation: To validate that the bean has been properly configured before it starts processing requests.
- Logging: To log a message indicating that the bean has been successfully initialized and is ready to be used.
Types of Methods to Annotate with @PostConstruct
- The method should be a void method.
- The method should not accept any arguments.
- The method should not throw a checked exception.
- The method should be non-static.