为什么使用@PostConstruct? [英] Why use @PostConstruct?

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

问题描述

在托管 bean 中,@PostConstruct 在常规 Java 对象构造函数之后调用.

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

为什么我要使用 @PostConstruct 来通过 bean 初始化,而不是使用常规构造函数本身?

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

推荐答案

  • 因为在调用构造函数时,bean 尚未初始化 - 即没有注入依赖项.在 @PostConstruct 方法中,bean 已完全初始化,您可以使用依赖项.

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

      因为这是保证这个方法在 bean 生命周期中只会被调用一次的契约.容器在其内部工作中可能会(尽管不太可能)多次实例化 bean,但它保证 @PostConstruct 只会被调用一次.

      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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆