Saturday, December 21, 2013

Spring HelloWorld DI(Dependency Injection) Example

Steps in NetBeans:

1)File->New Project->Java->Java Application
2)We need to add spring jars.We can add very easily in netbeans by browsing
    RightClick on Project->Libraries->AddLibrary->Choose Spring Framework 3.2.3 release

If you perform the above steps we are ready to dive in to our First Spring Example
Using DI (Dependency Injection)

Dependency Injection:

Let us take one example with out using spring

package org.jl;

/**
 *
 * @author Rishitha
 */
public class Circus {
  
    Parrot parrot;

    public Parrot getParrot() {
        return parrot;
    }

    public void setParrot(Parrot p) {
        this.parrot = p;
    }
  
  public static void main(String args[]){
      
        Circus c = new Circus();
        Parrot p = new Parrot();
        c.setParrot(p);
      
        p.getParrot().displayPicture();
      
      
    }
}

Let us see what are we doing and drawbacks of this approach:
---------------------------------------------------------------
1)Circus is dependent on parrot object and circus class is creating the dependency
    parrot using Parrot p = new Parrot(); and setting that to instance variable parrot
    c.setParrot(p);

2)Drawbacks:

    We are creating the dependency and setting that....So,Circus is tightly coupled with
     parent..

    What if I want to remove parrot from circus... and add pigeon in circus....and what
     code changes are required ?

3)You have to remove... Parrot p; and add Pigeon p; and remove existing parrot setter
    and getter and add new setter and getter for Pigeon...

4)We have to do lot of code changes... right ? What if Circus.. want to change everday
    from one bird to another

5)It is going to be horrible if you are the developer for... Circus...It is horrible because
    we are tightly coupling our code to some bird say pigeon or parrot.

6)Then.. think about how we can solve this problem...Interface can solve this problem..
   Instead of.. declaring parrot or pigeon or sparrow....

7)Declare one interface called Bird add  displayPicture and let Parrot and Pigeon implement
   Bird.

Let us see the new approach and classes

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jl;

/**
 *
 * @author Rishitha
 */
public class Circus {
   
    Bird bird;

    public Bird getBird() {
        return bird;
    }

    public void setBird(Bird b) {
        this.bird = b;
    }
   
   
           
      
    public static void main(String args[]){
       
       //Now see the new code with Animal interface
       Circus cir = new Circus();
      
            
       Bird par = new Parrot();
       cir.setBird(par);
      
       cir.getBird().displayPicture();
      
       //If I want to change the parrot to pigeon in circus
      
      
       
       Bird  pig = new Pigeon();
       cir.setBird(pig);
       cir.getBird().displayPicture();
       
    }
 
   
}

Advantages of this approach:
-----------------------------
You might have observed that... we are not even touching Circus class...
when the bird in the circus changes... Right ? This is the great advantage.....

Now you have made your circus loosely coupled..with bird interface coming
in to picture.You have avoided tight coupling with Parrot or Pigeon....

2)The drawaback of this is.. still you are creating the dependencies in main method

Now we will see how spring is going to help here...
------------------------------------------------------
Spring says.. that... you don't create your dependency like parrot or pigeon... Just
tell me which object you want...in xml file... I will inject.....and you can use it...



Now here is the code and xmls

springbeans.xml
----------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
">
  <bean id="circus" class="org.jl.Circus" >
    <property name="bird">
        <ref bean="pigeon"/>
    </property>
    </bean> 
   <bean id="parrot" class="org.jl.Parrot">
   </bean>
   <bean id="pigeon" class="org.jl.Pigeon">
   </bean>
  

   
</beans> 

2)Bird Interface

package org.jl;

/**
 *
 * @author Rishitha
 */
public interface Bird {
    public void displayPicture();
}

3)Parrot.java

package org.jl;

/**
 *
 * @author Rishitha
 */
class Parrot implements Bird{
   
    public void displayPicture(){
        System.out.println("I am parrot ");
       
    }
   
}

4)Pigeon.java

package org.jl;

/**
 *
 * @author Rishitha
 */
public class Pigeon implements Bird{

    @Override
    public void displayPicture() {
         System.out.println("I am Pigeon ");
    }
   
}


5)And finally Circus.java

package org.jl;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author Rishitha
 */
public class Circus {
   
    Bird bird;

    public Bird getBird() {
        return bird;
    }

    public void setBird(Bird b) {
        this.bird = b;
    }
   
   
           
      
    public static void main(String args[]){
       
       ApplicationContext ctx = new ClassPathXmlApplicationContext("springbeans.xml");
      
       Circus cir = (Circus)ctx.getBean("circus");
       cir.getBird().displayPicture();
      
       //If you want to change the bird to pigeon
       //In spring beans.xml change
       //<ref bean="parrot"/> to <ref bean="pigeon"/>
       //You need not even touch any code..... now
       
    }
 
   
}

Explanation:
-------------
AppicationContext is the spring container..

ApplicationContext reads the springbeans.xml and whenever you call getBean
it will check.. the bean with id creates that... and if there are any references for
that bean... it will create the referred bean and inject in to it and gives to the client

In our example when I say getBean("circus")

Spring creates circus object... and it checks that parrot/pigeon is being
referred by seeing <ref bean="parrot"/>

It will create parrot object invoke the setBird in Circus...
and returns... that Circus object which is having parrot/pigeon set.......


Hope you understood and enjoyed Dependency Injection example... :)
























    
    














No comments:

Post a Comment