In a managed bean, @PostConstruct
is called after the regular Java object constructor.
Why would I use @PostConstruct
to initialize by bean, instead of the regular constructor itself?
In a managed bean, @PostConstruct
is called after the regular Java object constructor.
Why would I use @PostConstruct
to initialize by bean, instead of the regular constructor itself?
bacause when the constructor is called, the bean is not yet initialized - i.e. no dependencies are injected. In the @PostConstruct
method the bean is fully initialized and you can use the dependnecies.
because this is the contract that guarantees that this method will be invoked only once in the bean lifecycle. It may happen (though unlikely) that a bean is instantiated multiple times by the container in its internal working, but it guarantees that @PostConstruct
will be invoked only once.
If your class performs all of its initialization in the constructor, then @PostConstruct
is indeed redundant.
However, if your class has its dependencies injected using setter methods, then the class's constructor cannot fully initialize the object, and sometimes some initialization needs to be performed after all the setter methods have been called, hence the use case of @PostConstruct
.