Why use @PostConstruct?

question:

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?


the response:

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

下边人的讨论

5 
in case the constructor itself autowires all dependencies - then the bean can also be fully initialized in the constructor (after setting manually all autowired fields). –  yair  Mar 20 '13 at 9:49
 
what's the case in which a bean's constructor may be called more than once? –  yair  Mar 20 '13 at 9:51
 
Probably something like "passivation". If the container decides to store the bean on the disk store and then restore it from there. –  Bozho  Mar 20 '13 at 9:57
8 
It's not that unlikely to see the constructor called multiple times. When the container instantiates a proxy, you will see that constructor is called at least once for the proxy and once for the real bean. –  marcus  Mar 17 

http://stackoverflow.com/questions/3406555/why-use-postconstruct


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值