Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of Spring Bean Initialization

Tags:

java

spring

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?

like image 276
Sandeep Jindal Avatar asked Jul 06 '10 15:07

Sandeep Jindal


People also ask

Does Bean order matter in Spring?

Order of bean initialization should not matter since the fields are injected after creating the bean. The only problem where the order will matter is when the bean is needed at constructor argument of other class, but Spring notices this and will solve it.

How are beans initialized in Spring?

Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed.

What is the correct Spring interface for initialization?

2.1.springframework. beans. factory. InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean have been set by the container.


1 Answers

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.

like image 183
dira Avatar answered Sep 21 '22 03:09

dira