开发者

Order of Spring Bean Initialization

I have multiple context files. Requirement is: one particular Bean (which makes some configuration changes) to be initialized first among rest of beans.

Is there a way to get this bean loaded first?

One option is using depends-on` attribute. But that would require updating al开发者_JS百科l the rest of the beans, thus seems not to be best solution.

Do we have better options?


IMHO you should wait until they fix https://jira.spring.io/browse/SPR-3948

One probable way is to use depends-on attribute. But again, I don't want to add this attribute in all the rest of the beans (this is probably the last resort for me).

Actually, you don't need to use depends-on on EACH AND EVERY BEAN in each and every applicationContext.xml.

Use <import /> in all "lower-lvel" applicationContext.xml to import the topmost applicationContext.xml.

And use depends-on attribute in each and ever bean definition only in topmost applicationContext.xml, except the <bean /> that you wanna load first.


I managed to influence the bean startup order by annotating my bean with @Order: See http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/annotation/Order.html


In can be meaningful to require ordering of beans, typically for technical beans (e.g. adding MBeans) to be loaded before business beans (just like it is proposed in http://jira.springframework.org/browse/SPR-3948)

Using BeanPostProcessor is another way to provide some ordering in your beans. Check AbstractApplicationContext.refresh() to see how it is enforced.


I'm not a Spring expert and likely to be shouted down by someone who is. But until then...

Where there's room for ambiguity, I would guess that Spring loads/applies stuff in the order it encounters it in the configuration files. Thus, as a first and simplest approximation, I would try to ensure that the thing you want initialized first is one of the first things in your configuration files.

If it's all hierarchical, then you'll want your "first" configurations to either be in the "main" file before the others are invoked or if possible in the first invoked file.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜