Why use @PostConstruct?

后端 未结 5 697
孤街浪徒
孤街浪徒 2020-11-22 11:49

In a managed bean, @PostConstruct is called after the regular Java object constructor.

Why would I use @PostConstruct to initialize by bean

5条回答
  •  花落未央
    2020-11-22 12:35

    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

    
    
        javax.annotation
        javax.annotation-api
        1.3.2
    
    

    Gradle

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

提交回复
热议问题