Spring Framework

Spring Projects

Spring Project 1

adplus-dvertising
Dependency Injection
Previous Home Next

Introduction: In case of DI (Dependency Injection) ,dependency of object are satisfied by IOC container on its own i.e IOC container are not ask to satisfied the dependency of an object.

Approach of Dependency Injection

There are two approach of Dependency Injection which are following:

  1. Constructor Dependency Injection
  2. Setter Dependency Injection

Constructor Dependency Injection: In this approach the IOC container provide the facility to satisfied the dependency of an object in mandatory case and IOC container inject the dependency through the constructor.

Setter Dependency Injection: In this approach the IOC container inject the dependency through the default constructor and setter method. This approach is used in the case of optional dependency.

Type of Dependency Injection

There are three type of dependency injection which are following:

  1. Dependency on primitive values (String is consider primitive by String).
  2. Dependency on Object.
  3. Dependency on Collection.

Dependency on primitive value: In the case of constructor injection, constructor-arg is the sub element of <bean ......> is used to specified the dependency of a bean i.e to be satisfied to a constructor this elements uses values and reference attribute which are used to specified value primitive type and object respectively.

Syntax:

<bean .................>   
<constructor-arg value="primitive or String"/>
<constructor-arg ref="Reference of a bean"/>
................
</bean>

Dependency on object: In the case of constructor injection, constructor-arg is the sub element of <bean ......> is used to specify the dependency of an object i.e to be satisfied the constructor-arg element uses reference of an attribute which are used to specify object respectively.

Syntax:

<bean .................>   
<constructor-arg >
<list><ref  bean="Reference of a bean"/>
................
</list></constructor-arg>
</bean>

Dependency on collection: In the case of constructor injection, constructor-arg is the sub element of <bean ......> is used to specify the dependency of a collection i.e to be satisfied the constructor-arg element uses list ,set and map sub element to specify the dependency of list ,set and map respectively.

Syntax:

<bean .................>   
<constructor-arg >
<list or set or map>
<Value></value>
................
</list or set or map></constructor-arg>
</bean>
Previous Home Next