What are the different types of dependency injection. Explain with examples.
2744
23-Jul-2011
James Smith
23-Jul-2011Setter Injection: Normally in all the java beans, we will use setter and getter method to set and get the value of property as follows:
String name;
public void setName(String a) {
name = a; }
public String getName() {
return name; }
}
<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,
String name;
public namebean(String a) {
name = a;
}
}
<bean id="bean1" class="namebean">
<constructor-arg>
<value>My Bean Value</value>
</constructor-arg>
</bean>