简体   繁体   中英

Order of bean initialization in Spring

I have the following beans in my Spring config 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 have noticed that in my application the elements in myList are in the following order: elem4, elem1, elem3, elem2. I was expecting that the elements in my list will be in the order I set when I declared the ref beans ( elem1, elem2, elem3, elem4). Is there an order in which Spring initializes beans? Is there a way I can specify an order for the elements in my list?

The spring does respect the order you gave in the list. The elements in the list would exactly be the [elem1,elem2,elem3,elem4] as you specified. Otherwise, you are doing something wrong, can you show the code which prints you the different order?

The order of bean initialization however may be different and depends on bean dependencies, so, 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, the InnerBean will be initialized first, then during HolderBean initialization it will be injected into HolderBean.

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