如何为Spring Beans选择不同的初始化策略?

时间:2012-09-26 11:21:52

标签: spring javabeans lifecycle

此日志中捕获了默认bean初始化策略:

[Wed Sep 26 13:10:35 CEST 2012]: <Thread main, Class is.test.spring.Instance> setBeanName() asda
[Wed Sep 26 13:10:35 CEST 2012]: <Thread main, Class is.test.spring.ExecutableImpl> ID: fdsa, message: create()
[Wed Sep 26 13:10:35 CEST 2012]: <Thread main, Class is.test.spring.ExecutableImpl> ID: fdsa, message: start()
[Wed Sep 26 13:10:35 CEST 2012]: <Thread main, Class is.test.spring.ExecutableImpl> ID: fdsaa, message: create()
[Wed Sep 26 13:10:35 CEST 2012]: <Thread main, Class is.test.spring.ExecutableImpl> ID: fdsaa, message: start()
[Wed Sep 26 13:10:35 CEST 2012]: <Thread Thread-1, Class is.test.spring.ExecutableImpl> ID: fdsaa, message: stop()
[Wed Sep 26 13:10:35 CEST 2012]: <Thread Thread-1, Class is.test.spring.ExecutableImpl> ID: fdsaa, message: destroy()
[Wed Sep 26 13:10:35 CEST 2012]: <Thread Thread-1, Class is.test.spring.ExecutableImpl> ID: fdsa, message: stop()
[Wed Sep 26 13:10:35 CEST 2012]: <Thread Thread-1, Class is.test.spring.ExecutableImpl> ID: fdsa, message: destroy()

在调用start()方法之后,认为Bean已完全初始化。现在我想要做的是同步初始化所有bean。在每个其他bean完成其步骤之前,没有bean会进入下一个初始化步骤。结果日志看起来像这样:

[Wed Sep 26 13:10:35 CEST 2012]: <Thread main, Class is.test.spring.Instance> setBeanName() asda
[Wed Sep 26 13:10:35 CEST 2012]: <Thread main, Class is.test.spring.ExecutableImpl> ID: fdsa, message: create()
[Wed Sep 26 13:10:35 CEST 2012]: <Thread main, Class is.test.spring.ExecutableImpl> ID: fdsaa, message: create()
[Wed Sep 26 13:10:35 CEST 2012]: <Thread main, Class is.test.spring.ExecutableImpl> ID: fdsa, message: start()
[Wed Sep 26 13:10:35 CEST 2012]: <Thread main, Class is.test.spring.ExecutableImpl> ID: fdsaa, message: start()
[Wed Sep 26 13:10:35 CEST 2012]: <Thread Thread-1, Class is.test.spring.ExecutableImpl> ID: fdsa, message: stop()
[Wed Sep 26 13:10:35 CEST 2012]: <Thread Thread-1, Class is.test.spring.ExecutableImpl> ID: fdsaa, message: stop()
[Wed Sep 26 13:10:35 CEST 2012]: <Thread Thread-1, Class is.test.spring.ExecutableImpl> ID: fdsa, message: destroy()
[Wed Sep 26 13:10:35 CEST 2012]: <Thread Thread-1, Class is.test.spring.ExecutableImpl> ID: fdsaa, message: destroy()

关于如何实现这一目标的任何想法?

此外,是否可以在后台线程中处理所有初始化(每个bean的每个生命周期步骤)?我希望初始化会非常耗时...

1 个答案:

答案 0 :(得分:0)

关于如何实现这一目标的任何想法?

您可以使用<bean depends-on="..."/>表示法或使用注释org.springframework.context.annotation.DependsOn来管理Spring生命周期。

此外,是否可以在后台线程中处理所有初始化(每个bean的每个生命周期步骤)?

在bean的init()或destroy()方法中(通过InitializingBean / DisposableBean或通过PostConstruct / PreDestroy),您可以创建一个不同的线程来初始化/销毁它。