Dependency Injection in Spring

Dependency Lookup

The Dependency Lookup is an approach where we get the resource after demand. There can be various ways to get the resource for example:

  1. A obj = new AImpl();

In such way, we get the resource(instance of A class) directly by new keyword. Another way is factory method:

  1. A obj = A.getA();

This way, we get the resource (instance of A class) by calling the static factory method getA().

Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:

  1. Context ctx = new InitialContext();
  2. Context environmentCtx = (Context) ctx.lookup(“java:comp/env”);
  3. A obj = (A)environmentCtx.lookup(“A”);

There can be various ways to get the resource to obtain the resource. Let’s see the problem in this approach.

Dependency Injection

The Dependency Injection is a design pattern that removes the dependency of the programs. In such case we provide the information from the external source such as XML file. It makes our code loosely coupled and easier for testing. In such case we write the code as:

  1. class Employee{
  2. Address address;
  3. Employee(Address address){
  4. this.address=address;
  5. }
  6. public void setAddress(Address address){
  7. this.address=address;
  8. }
  9. }

In such case, instance of Address class is provided by external souce such as XML file either by constructor or setter method.

Two ways to perform Dependency Injection in Spring framework

Spring framework provides two ways to inject dependency

  • By Constructor
  • By Setter method

Courtesy: http://www.javatpoint.com/dependency-injection-in-spring

Leave a Reply

Your email address will not be published. Required fields are marked *


× eight = 64

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>