Spring DI via Constructor

  • Facebook
  • Google
  • LinkedIn
  • Twitter

In Constructor based Dependency Injection, Objects define their dependencies via Constructor argument tag and Container invoke Constructors to set these arguments in object.

Example of Spring DI via Constructor

MyColor.java

package com.javatutsworld;
 
public interface MyColor {
 
   public void printColor(); 
}

GreenColor.java

package com.javatutsworld;
 
public class GreenColor implements MyColor {
 
 @Override
 public void printColor() {
   System.out.println("It is green color");
  }
}

ColorSet.java

Here is ColorSet, you are using dependency injection via constructor in this class:

package com.javatutsworld;
 
public class ColorSet{
 
  MyColor color;
     
  public void pringColor(){
    this.color.printColor();
  }
     
  /**
   * dependency injection through constructor
   * @param myColor
  */
  public ColorSet(MyColor myColor){
    this.color = myColor;
  }
}

Following is the configuration file applicationContext.xml which has configuration for the constructor-based injection: If you closely monitor constructor-arg tag, you are passing greenColor reference to the constructor as an input parameter.


<?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:p="http://www.springframework.org/schema/p"  
  xsi:schemaLocation="http://www.springframework.org/
  schema/beans  
  http://www.springframework.org/schema/beans/
  spring-beans-3.0.xsd"> 
 
<bean id="colorSet" class="com.javatutsworld.ColorSet">
  <constructor-arg>
   <ref bean="greenColor"/>    
  </constructor-arg>
</bean>
<bean id="greenColor" class="com.javatutsworld.GreenColor"/>
</beans>

package com.javatutsworld;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.
ClassPathXmlApplicationContext;
 
import com.javatutsworld.ColorSet;
 
public class TestClient {
 
public static void main(String a[]){
         
 @SuppressWarnings("resource")
 ApplicationContext context = new 
 ClassPathXmlApplicationContext("applicationContext.xml");
 ColorSet clrSet = (ColorSet)context.getBean("colorSet");
   clrSet.pringColor();
}
}
Output:
It is green color
      Advertisements