开发者

Spring: how to initialise Bean A after load of Bean B is complete?

I have a BeanA which whose constructor requires BeanB. Once BeanB has been instantiated (and its properties set), I'd like to invoke BeanB.init()

Is there a wa开发者_Python百科y of doing this?

An alternative would be to have BeanB.init() invoked after all beans in the context have been created.

Cheers!


You can use init-method in your applicationContext.xml in order to specify an init method. If you want a bean to instantiate after another, you can use depends-on, even though any ref element (in this example inside constructor-args) will implicitly place a dependency.

This would initialize firstly Bean B with an init method and, when finished, use it in as constructor argument to A.

<!-- Bean B -->
<bean id="beanB" 
    class="classB"
    init-method="init"
/>

<!-- Bean A -->
<bean id="beanA" 
    class="classA"
    init-method="anotherInit">
        <constructor-arg ref="beanB"/>
    </bean>


You can make BeanB implement InitializingBean. The drawback of this is that you're creating a dependency between BeanB and Spring, which is not great.

I think a better approach would be to inject all the dependencies in the constructor and call init form it. In this way, you don't need to tie your class to Spring.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜