Spring Constructor Injection

Constructor Injection in spring

Spring Constructor Injection

Constructor Injection in spring is performed by Spring IoC container by invoking the constructor of Object with number of arguments, each object represents dependency. Dependency Injection is the process where each object define their dependencies with different injection methods.

One of them is Constructor based dependency Injection. Constructor based dependency Injection is nearly equivalent to calling a static factory method in order to construct the bean.  


Constructor Injection in spring

Below is a Simple POJO class that has no dependencies (loose coupled).

public class ServiceBean {

 private UserDao userDao;

 public ServiceBean(UserDao userDao) {
 this.userDao = userDao;
 }
}

How container resolves the dependencies

Constructor argument resolution matching occurs using the arguments type. When we pass arguments to the constructor, then container try to match their type. And the order in which we supply the arguments to the constructor during the bean definition is the order of supplied arguments.

For Example

public class BeanTest {

 public BeanTest(Child1 child1, Child2 child2) {
 }
}

Bean definition
<beans>
 <bean id="beanTest" class="com.package.BeanTest">
 <constructor-arg ref="child1"/>
 <constructor-arg ref="child2"/>
 </bean>
 <bean id="child1" class="com.package.Child1"/>
 <bean id="child2" class="com.package.Child2"/>
</bean>


Passing simple types as argument


Similarly you can pass simple types such as int, float, String values to constructor. But There is one thing need to understand in case of these types that is in case of reference, the type is known but in case of simple argument, the type is not determined by the container.

So in that case, we need to pass the type values as well.

Consider this example
<beans>
 <bean id="beanTest" class="com.package.BeanTest">
 <constructor-arg type="int" value="2300"/>
 <constructor-arg type="java.lang.String" value="Welcome to spring"/>
 </bean>
</bean>


Using index attribute to determine the constructor argument


You can also specify the index or order in which arguments should be resolved by IoC container.
<beans>
 <bean id="beanTest" class="com.package.BeanTest">
 <constructor-arg index="0" value="2300"/>
 <constructor-arg index="1" value="Welcome to spring"/>
 </bean>
</bean>


Using name attribute to determine the constructor argument


Another method is to use names instead of type or index as following.
<beans>
 <bean id="beanTest" class="com.package.BeanTest">
 <constructor-arg name="age" value="23"/>
 <constructor-arg name="name" value="Ashish"/>
 </bean>
</bean>

Related Post

Leave a Reply

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