Why use @PostConstruct? Why use @PostConstruct? java java

Why use @PostConstruct?


  • because 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 dependencies.

  • 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.


The main problem is that:

in a constructor, the injection of the dependencies has not yet occurred*

*obviously excluding Constructor Injection


Real-world example:

public class Foo {    @Inject    Logger LOG;    @PostConstruct    public void fooInit(){        LOG.info("This will be printed; LOG has already been injected");    }    public Foo() {        LOG.info("This will NOT be printed, LOG is still null");        // NullPointerException will be thrown here    }}

IMPORTANT: @PostConstruct and @PreDestroy have been completely removed in Java 11.

To keep using them, you'll need to add the javax.annotation-api JAR to your dependencies.

Maven

<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api --><dependency>    <groupId>javax.annotation</groupId>    <artifactId>javax.annotation-api</artifactId>    <version>1.3.2</version></dependency>

Gradle

// https://mvnrepository.com/artifact/javax.annotation/javax.annotation-apicompile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'


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.