Types of IOC(Inversion of Control) or DI(Dependency Injection)

There are two types of dependency injection: setter injection and constructor injection.

Setter Injection: Normally in all the java beans, we will use setter and getter method to set and get the value of property as follows:

public class namebean {
String name;    
public void setName(String a) {
             name = a;
}    
public String getName() {    
return name;
}
}

We will create an instance of the bean ‘namebean’ (say bean1) and set property as bean1.setName(“tom”); Here in setter injection, we will set the property ‘name’ in spring configuration file as showm below:

<bean id=”bean1″ class=”namebean”>

<property name=”name” > <value>tom</value> </property>

</bean>

The subelement <value> sets the ‘name’ property by calling the set method as setName(“tom”); This process is called setter injection. To set properties that reference other beans <ref>, subelement of <property> is used as shown below,

<bean id=”bean1″ class=”bean1impl”>
<property name=”game”>
<ref bean=”bean2″/>
</property>
</bean>
<bean id=”bean2″ class=”bean2impl” />

Constructor injection: For constructor injection, we use constructor with parameters as shown below,

public class namebean {
String name;
public namebean(String a) {
name = a;
}
 }

We will set the property ‘name’ while creating an instance of the bean ‘namebean’ as namebean bean1 = new namebean(“tom”);

Here we use the <constructor-arg> element to set the the property by constructor injection as

<bean id=”bean1″ class=”namebean”>           <constructor-arg><value>My Bean Value</value></constructor-arg></bean>