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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章