This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: Why use @postconstruct?

In a managed Bean, @Postconstruct is called after the regular Java object constructor.

Why do I use @PostConstructBean for initialization instead of the regular constructor itself?

Answer 1:

Because when the constructor is called, the bean is not initialized – that is, no dependencies are injected. In the @Postconstruct method, the bean is fully initialized and you can use dependencies.

This is the convention that guarantees that this method will be called only once in the bean life cycle. It is possible (though unlikely) that the container instantiates the bean multiple times in its internal work, but it guarantees that @PostConstruct will only call it once.

The PostConstruct annotation is used on methods that need dependency injection to complete in order to execute any initialization. This method must be called before the class can be put to use. All classes that support dependency injection must support this annotation.

Jsr-250 Chapter 1. 2.5 javax.mail. The annotation. PostConstruct

For example

public class Foo {

    @Inject
    Logger LOG;

    @PostConstruct
    public void fooInit(a){
        LOG.info("This will be printed; LOG has already been injected");
    }

    public Foo(a) {
        LOG.info("This will NOT be printed, LOG is still null");
        // NullPointerException will be thrown here}}Copy the code

Important: @postConstruct and @Predestroy have been completely removed in Java 11.

To continue using them, you need to add the Javax.annotation-API JAR to your dependencies.

Use the following method in Maven

<! -- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.32.</version>
</dependency>
Copy the code

Use the following method in Gradle

// https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api
compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'
Copy the code