Why use @PostConstruct?

后端 未结 5 817
孤街浪徒
孤街浪徒 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:20

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

提交回复
热议问题