In a managed bean, @PostConstruct
is called after the regular Java object constructor.
Why would I use @PostConstruct
to initialize by bean
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.
javax.annotation
javax.annotation-api
1.3.2
// https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api
compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'