Spring bean initialization order

I have the following beans in my Spring configuration file:

<bean id="myList" class="java.util.ArrayList"> <constructor-arg> <list> <ref bean="elem1"/> <ref bean="elem2"/> <ref bean="elem3"/> <ref bean="elem4"/> </list> </constructor-arg> </bean> <bean id="elem4" class="myClass"> <property name="title" value="random4"/> </bean> <bean id="elem1" class="myClass"> <property name="title" value="random1"/> </bean> <bean id="elem3" class="myClass"> <property name="title" value="random3"/> </bean> <bean id="elem2" class="myClass"> <property name="title" value="random2"/> </bean> 

I noticed that in my application, the elements in myList are in the following order: elem4, elem1, elem3, elem2. I was expecting the items in my list to be in the order I set when I declared ref beans (elem1, elem2, elem3, elem4). Is there an order in which Spring initializes beans? Is there a way to specify the order for items in my list?

+4
source share
1 answer

spring follows the order you specify in the list. The elements in the list will be exactly the elements [elem1, elem2, elem3, elem4], as you indicated. Otherwise, you are doing something wrong, can you show code that prints a different order to you?

However, the order of initialization of the bean may be different and depends on the dependencies of the bean, therefore, for example, if you have two beans

 <bean id="holder" class="my.HolderBean" lazy-init="false"> <property name="inner" ref="inner"/> </bean> <bean id="inner" class="my.InnerBean" lazy-init="false"/> 

Then, regardless of the xml definition order, an InnerBean will be initialized first, then during HolderBean initialization it will be inserted into the HolderBean.

0
source

All Articles