Spring Spring Core

Control Bean Creation Order in Spring

Generally we provide dependencies of a Bean using the <ref/> attribute in Spring Configuration Meta-Data as like below.

<bean id="employeeController" class="net.geekcoders.example.EmployeeController">
		<constructor-arg ref="employeeManager"></constructor-arg>
	<bean id="employeeManager" class="net.geekcoders.example.EmployeeManager">

The “employeeController” bean is directly depending on the “employeeManager” bean.

But, all the dependencies of a Bean will not direct like this. Some dependencies will be indirectly referred into the Bean Object.

For Example : EmployeeController class has to process employee data with the help of EmployeeManager class methods and has to save it in DB. 

Here, EmployeeManager will process required data for EmployeeController and return the data. Now we have to save the processed data into DB. For this we need employeeDAO created and ready to use. 

If it is not created at the time of accessing it from EmployeeController Bean or from EmployeeManager Beans, it will throw NullPointerException. To avoid such exceptions we can define ordering of Bean creation in Configuration itself. 

Let us see with Diagram and Example Code below.

Configuration Meta-Data

<bean id="employeeController" class="net.geekcoders.example.EmployeeController"
	<constructor-arg ref="employeeManager"></constructor-arg>
<bean id="employeeManager" class="net.geekcoders.example.EmployeeManager">
<bean id="employeeDAO" class="net.geekcoders.example.EmployeeDAO"></bean>

From the above configuration you can see the <depends-on/> attribute added with employeeDAO value.

So the Container will refer to the depends-on attribute and creates EmployeeDAO first and then create EmployeeDAO Bean. It will resolve the Bean Ordering Problem.

You can provide more than one Bean reference separated by commas. 

<bean id="employeeController" class="net.geekcoders.example.EmployeeController" depends-on="employeeDAO,employerDAO">
	<constructor-arg ref="employeeManager"></constructor-arg>

If so, the employeeDAO, employerDAO Beans will be created and assembled at first. 

That’s all for now on Bean Creation Order in Spring!!!

Happy Reading!!!

Leave a Reply

Your email address will not be published. Required fields are marked *