您的位置:首页 > 其它

Why use @PostConstruct?

2016-05-19 11:58 183 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: