本文介绍了为什么要使用@PostConstruct?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在受管Bean中,通过bean初始化,而不是常规构造函数本身?

解决方案

因为当构造函数被调用时,bean还没有被初始化 - 即没有注入依赖关系。在 @PostConstruct 方法中,bean被完全初始化,您可以使用依赖关系。


  • 因为是确保在Bean生命周期中仅调用此方法一次的合同。它可能发生(尽管不太可能),bean在其内部工作中被容器多次实例化,但它保证 @PostConstruct 将仅被调用一次。



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

    Why would I use @PostConstruct to initialize by bean, instead of the regular constructor itself?

    解决方案

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

    这篇关于为什么要使用@PostConstruct?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    07-29 21:08