Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Saturday, January 3, 2015

Dependency Injection with Spring Framework

Before you read this post I hope you understand about dependency injection  and  Spring Framework Initial Configuration.

On my previous post we tried simple dependency injection in Java, let's call it Programmatic way. Sometimes we need to make it configurable. Spring offers dependency injection with Declarative way.

Here we go :

1. Jacket.java

Create Java class in package com.brewer :

 package com.brewer;  

 public class Jacket {  

      private String color;  //will be injected

      public Jacket(){  
      }  
      public Jacket(String color){  //used for constructor injection
           this.color = color;  
      }  
      public String getColor() {  
           return color;  
      }  
      public void setColor(String color) { //used for setter method injection  
           this.color = color;  
      }  
      @Override  
      public String toString() {  
           return "Jacket [color=" + color + "]";  
      }  
 }  



2.  bean.xml

Create bean.xml in package com.brewer :

 <?xml version="1.0" encoding="UTF-8"?>  
 <beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">  
      <bean id="jacketConst" class="com.brewer.Jacket">  
           <constructor-arg>  
                <value>blue#87CEEB</value>  
           </constructor-arg>  
      </bean>  
      <bean id="jacketSetter" class="com.brewer.Jacket">  
           <property name="color" value="blue#87CEEB" />  
      </bean>   
 </beans>  

bean.xml contains list of beans and will loaded by Spring. Spring will save those beans in Application Context.


3. Test.Java

Create Test class in package com.brewer :

 package com.brewer;  

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

 public class Test {  
      public static void main(String[] args) {  
           ApplicationContext appContext = new ClassPathXmlApplicationContext("com/brewer/bean.xml"); 
           Jacket jacket = (Jacket) appContext.getBean("jacketConst");  
           System.out.println("Constructor injection : "+jacket.toString());  
           Jacket jacket2 = (Jacket) appContext.getBean("jacketSetter");  
           System.out.println("Method Setter injection : "+jacket2.toString());  
      }  
 }  




Happy Coding :)

Tuesday, December 16, 2014

Dependency Injection in Java

Source picture: http://mealsandmovesblog.com


It will be nice if we know what dependency injection is before we implement it in Java .

What is Dependency Injection?

Dependency Injection is a design pattern.

Every component of an application have a dependency with another component. Let me explain with a simple example below :

 public class Jacket {  
    String color = "blue"+"#87CEEB";   
    public String getColor(){  
        return color;  
    }  
 }  

"Jacket" has a dependency with String. In other word, Jacket can not be created if String object does not exist.
Jacket has tightly coupled with String because Jacket knows how to create String object. Problem will occur if the object creation is complex, and not as a simple as String object. For more complex example, see "Connection" object creation below :

 public static void main() {  
           Connection con = null;  
           String url = "";  
           String user = "";  
           String password = "";  
           try {  
                Class.forName("oracle.jdbc.driver.OracleDriver");  
                try {  
                     con = DriverManager.getConnection(url, user, password);  
                } catch (SQLException e) {  
                     // exception statement here  
                }  
           } catch (ClassNotFoundException e) {  
                e.printStackTrace();  
           }  
      }  

You can imagine if that code appear in every class, your code would be a mess.

From two examples above we can resume the problem of dependency :
  1. High Coupling
  2. Low Cohesion
Dependency Injection comes to solve those problem. 

How dependency injection works?
1. Create String object color outside Jacket
2. Create Jacket object
3. Inject  color Object through constructor or setter method

  So practically, here is the example of dependency injection :

 public class Jacket {  
    private String color;  
    public Jacket(){  
    }  
    public Jacket(String color){ //inject dependency through constructor  
       this.color = color;  
    }  
    public void setColor(String color){ //inject dependency through setter method  
       this.color = color;  
    }  
    public String getColor(){  
        return color;  
    }  
 }  
 public class Main(){  
     public static void main(String []args){  
        String color = "blue"+"#87CEEB"; // create color String object  
        Jacket jacket = new Jacket (color); //inject through constructor  
        Jacket jacket2 = new Jacket();  
        jacket2.setColor(color); //inject through setter method  
    }  
 }   


Next post we will look dependency injection in Spring Framework.


Happy coding :)