How to find the sequence of beans initialised by spring

1.1k views Asked by At

My ApplicationContext has beans that are autowired as well as beans that are configured in application-Context.xml file. I want to know the sequence of bean initialization by spring.

I wanted to know this because: (I know this is a known and popular issue in stackoveflow..but could not get a solution!!) I have created SessionBean in application-Context.xml. Now tring to autowire this bean in DaoImpl file. sessionBean is showing null there. May be its sessionFactory is not initialised till then.

*I have tried using @DependsOn("SessionFactory") with failure.

So my questions are:

1)How to find the sequence of beans initialised by spring.
2)How do say to spring to initilise sessionfactory before  initialising my DAOImpl class.

Please help as i am struck!!

Thanks in advance.

2

There are 2 answers

0
Kaushik Patel On

Spring auto determines the sequence of Bean initialization by looking at if all the dependencies of the said bean are initialized or not.

Your case seems like you are not using the spring initialized bean of DaoImpl class whereas creating a new Object of the class on you own.

Try creating the bean of the DaoImpl class and use the bean.

0
Nivi On

here is the answer of your 1st question-

<bean id="OutputHelper" class="com.mkyong.output.OutputHelper">
        <property name="outputGenerator" >
            <ref bean="CsvOutputGenerator"/>
        </property>
</bean>

<bean id="CsvOutputGenerator" class="com.mkyong.output.CsvOutputGenerator">
        <property name="name"value="hi"/ >
</bean>

say this is the bean defined in your spring config file 
so what spring container will try to do is -   
1. 1st it will try to load i.e `OutputHelper` class  
2. While loading the class it will check if there is any dependency                           
3. if yes,It will stop life cycle of main bean i.e `OutputHelper` and try to load dependent bean 'CsvOutputGenerator'.
- If current bean does not have any dependency then it will load the bean and moved back to main bean life cycle process.

step 2 &3 will be applicable for all the bean mentioned in config file.