Home > DeveloperSection > Interviews > What are the different types of dependency injection. Explain with examples.

Posted on    July-23-2011 7:57 AM

 Java Java 
 1 Answer(s)
  1358  View(s)
Rate this:

James Smith

Total Post:79

Posted on    July-23-2011 12:00 AM

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" >
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"/>
<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">
<value>My Bean Value</value>

Don't want to miss updates? Please click the below button!

Follow MindStick