简体   繁体   中英

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 all 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.

In can be meaningful to require ordering of beans, typically for technical beans (eg 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.

我设法通过使用@Order注释我的bean来影响bean启动顺序:请参阅http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/annotation/Order.html

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM