Wednesday, 20 April 2016

How to use different type of Dependency injection ?



1. Setter Injection

Each of the objects that the class depends upon will have a setter and the IoC container will use the setters to provide the resource at run-time.
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 shown below : 
<bean id="bean1"  class="namebean">
   <property name="name" value="Tom" />
</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" />


2. Constructor Injection

IoC container uses the constructor to inject the dependency.
One of the advantages of Constructor Injection is that all the dependencies are declared in one go.
public class namebean {
  String name;
  public namebean(String a) {   // Constructor
     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 (multiple tags for multiple arguments) to set the the property by constructor injection as :
<bean id="bean1 class="namebean">
  <constructor-arg value="My Bean Value" />
</bean>

In case of multiple arguments, use this tag multiple times :
  <constructor-arg value="My Bean Value" />
  <constructor-arg value="20" />
You can explicitly define the data type also :
  <constructor-arg type="java.lang.String" value="Hello" />
  <constructor-arg type="int" value="20" />

You can define order of constructor arguments also :
  <constructor-arg index="0" value="My Bean Value" />
  <constructor-arg index="1" value="20" />


Interface Injection

Interface Injection provides the concrete implementations of an interface to the dependent object according to the configuration.
Any of the implementations of the interface can be injected, whereas with the other two, the object of the class specified is injected.
Spring does not provide direct support for Interface Injection.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.