Rajinder Menu

Constructor-Based Dependency Injection


In Constructor based dependency injection, Spring Container uses one of the constructors defined in the class in order to inject dependencies for that class.

In constructor based DI, instead of <property name="prop_name" value="prop_value"/>  tag, you use <constructor-arg  name="arg_name"  value="arg_value"/> tag in the bean definition.

For example, suppose you have a Car class defined as:

public class Car {
    private String make;
    private String model;
    private int year;
    private Engine engine;

/*Spring Container will use this constructor to inject dependencies*/
public Car(String make,String model,int year){
    this.engine=engine;
    this.model=model;
    this.make=make;
    this.year=year;
}
//setters and getters...
}

In the above class there is a constructor which has three arguments namely make, model, year.

Now in order inject these dependencies you will define your bean as :

<bean id="myCar"  class="exampes.spring.di.Car">
    <constructor-arg name="make" value="Maruti Suzuki"/>
    <constructor-arg name="model" value="Wagon R"/>
   <constructor-arg name="year" value="2012"/>

</bean>

In above bean definition we have  injected only primited values . Suppose Car class has a constructor :

public Car(String make,String model,int year, Engine engine){
...
this.engine=engine;
}

Here constructor has one more argument which is a reference to an instance of some other class Engine.

Now your bean definition will get changed as:

<bean id="myCar"  class="exampes.spring.di.Car">
   <constructor-arg name="make" value="Maruti Suzuki"/>
   <constructor-arg name="model" value="Wagon R"/>
   <constructor-arg name="year" value="2012"/>
  <constructor-arg name="engine" ref="myEngine"/>
</bean>

where myEngine is some other bean defined in configuration file as:

<bean id="myEngine" class="examples.spring.di.Engine">
...
</bean>

You can find full example here.

TODO: ambiguities in constructor resolving.




I would like to know your comments and if you liked the article then please share it on social networking buttons.


Setter-Based Dependency Injection


In Setter based dependency injection Spring Container uses setter methods of the properties defined in the class to inject their values.

<property name="prop_name" value="prop_value"/>  tag is used in the bean definition to provide values for properties in the class.

For example, suppose you have a Car class defined as:

public class Car {
    private String make;
    private String model;
    private int year;

    /*Spring Container will use this setter method for injecting value for 'make' property*/
    public void setMake(String make){
        this.make=make;
    }
 
    public String getMake(){
        return make;
    }

//setters and getters for other properties...

}

Above class has three properties namely make, model, year.

To inject values for these properties you will define your bean in bean configuration file as :

<bean id="myCar" class="examples.spring.di.Car">
   <property name="make" value="Maruti Suzuki"/>
   <property name="model" value="Wagon R"/>
   <property name="year" value="2012"/>
</bean>


In above bean definition we have  injected only primitive values . Suppose Car class has one more property of type Engine (Let Engine is some other class) as:

public class Car {
    private String make;
    private String model;
    private int year;
   private Engine engine;

//setters and getters...

}

Then your bean defintion would become:

<bean id="myCar" class="exampes.spring.di.Car">
       <property name="make" value="Maruti Suzuki"/>
      <property name="model" value="Wagon R"/>
      <property name="year" value="2012"/>
     <property name="engine" ref="myEngine"/>
</bean>

where myEngine is some other bean defined in bean configuration file as:

<bean id="myEngine" class="examples.spring.di.Engine">
.....
</bean>

Note that we have used ref attribute instead of value attribute in. Attribute ref is used to point to the id of some other bean instead of primitive values (like String, int etc).

You can find full example here.



I would like to know your comments and if you liked the article then please share it on social networking buttons.


Spring Tutorial

Articles | Spring Examples

Dependency Injection Into Collection and Array Type Properties


This tutorial shows how to inject values into collection type properties of Spring beans i.e properties of type Collection,List, Set etc.

This example is using following technologies:

1) Spring-framework-3.0.2.RELEASE
2) Eclipse Java EE IDE Helios Release (Eclipse version 3.6)
3) Java SE 6  

Jars Used:
 org.springframework.beans-3.0.2.RELEASE.jar
 org.springframework.core-3.0.2.RELEASE.jar
 org.springframework.context-3.0.2.RELEASE.jar
 org.springframework.asm-3.0.2.RELEASE.jar
 org.springframework.expression-3.0.2.RELEASE.jar
 commons-logging-1.1.1.jar


Step 1: Create a new Project in eclipse.


Create a new project in eclipse by going to File > New > Java Project and name it as SpringDICollections.

Project structure in eclipse is shown below:




There are four files used in this program:

1)      BlogPost.java
2)      Image.java
3)      MainApp.java
4)      ApplicationContext.java

Step2: Add the source code.

Add the following source code in eclipse.

Blogpost.java

package examples.spring.di;

import java.util.List;
import java.util.Set;

public class BlogPost {
   /* List Type properties */
   List<String> tagsAssignedAsList;
   List<Image> imagesInBlogAsList;

   /* Set type properties*/
   Set<String> tagsAssignedAsSet;
   Set<Image> imagesInBlogAsSet;
  
   /* Array*/
   String[] authors;
  
   
    public void setTagsAssignedAsList(List<String> tagsAssignedAsList){
        this.tagsAssignedAsList=tagsAssignedAsList;
    }
   
    public List<String> getTagsAssignedAsList(){
        return (List<String>)tagsAssignedAsList;
    }
   
    public void setImagesInBlogAsList(List<Image> imagesInBlogAsList){
        this.imagesInBlogAsList=imagesInBlogAsList;
    }
   
    public List<Image> getImagesInBlogAsList(){
        return (List<Image>)imagesInBlogAsList;
    }
   
    public void setTagsAssignedAsSet(Set<String> tagsAssignedAsSet){
        this.tagsAssignedAsSet=tagsAssignedAsSet;
    }
   
    public Set<String> getTagsAssignedAsSet(){
        return (Set<String>)tagsAssignedAsSet;
       
    }
   
    public void setImagesInBlogAsSet(Set<Image> imagesInBlogAsSet){
        this.imagesInBlogAsSet=imagesInBlogAsSet;
    }
   
    public Set<Image> getImagesInBlogAsSet(){
        return (Set<Image>)imagesInBlogAsList;
    }

    public void setAuthors(String[] authors){
        this.authors=authors;
    }
   
    public String[] getAuthors(){
        return authors;
    }
   
    public void showBlogTags(){
        System.out.println("Tags Assigned To Blog As List:: ");   
        for(String tag:tagsAssignedAsList){
            System.out.println(tag);           
        }
   
        System.out.println("**************");
       
        System.out.println("Tags Assigned To Blog As Set:: ");   
        for(String tag:tagsAssignedAsSet){
        System.out.println(tag);           
        }
    }
   
    public void showBlogImages(){
        System.out.println("**************");
        System.out.println("Images Used In Blog As List:: ");   
        for(Image img:imagesInBlogAsList){
            System.out.println("Image ID:"+img.getImageId());           
        }
   
        System.out.println("**************");
       
        System.out.println("Images Used In Blog As Set:: ");   
        for(Image img:imagesInBlogAsSet){
            System.out.println("Image ID:"+img.getImageId());           
         }   
        }
    public void showBlogAuthors(){
        System.out.println("**************");
       
        System.out.println("Authors of Blog:: ");
       
        for(String author:authors){
            System.out.println(author);           
         }
    }
}


Image.java
package examples.spring.di;

public class Image {
    String imageId;
    String imageFileName;
  
    public void setImageId(String imageId){
        this.imageId=imageId;
    }
  
    public String getImageId()    {
        return imageId;
    }
  
    public void setImageFileName(String imageFileName){
        this.imageFileName=imageFileName;
    }
  
    public String getImageFileName()    {
        return imageFileName;
    }
  
}


MainApp.java
package examples.spring.di;

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

public class MainApp {    public static void main(String args[]){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("resources/ApplicationContext.xml");
        BlogPost myBlog=(BlogPost)ctx.getBean("myBlogPost");
        myBlog.showBlogTags();
        myBlog.showBlogImages();
        myBlog.showBlogAuthors();
        }
}


ApplicationContext.java
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="image1" class="examples.spring.di.Image">
   <property name="imageId" value="image1"/>
   <property name="imageFileName" value="ImageFile1"/>
</bean>

<bean id="image2" class="examples.spring.di.Image">
   <property name="imageId" value="image2"/>
  <property name="imageFileName" value="ImageFile2"/>
</bean>

<bean id="image3" class="examples.spring.di.Image">
  <property name="imageId" value="image3"/>
  <property name="imageFileName" value="ImageFile3"/>
</bean>

<bean id="image4" class="examples.spring.di.Image">
  <property name="imageId" value="image4"/>
  <property name="imageFileName" value="ImageFile4"/>
</bean>


<bean id="myBlogPost" class="examples.spring.di.BlogPost">

    <!-- Injecting 'primitive values'  in List type property-->
    <property name="tagsAssignedAsList">
     <list>
         <value>Java</value>
         <value>Java</value> <!-- Duplicates will be accepted in List-->
         <value>Spring</value>
         <value>Spring-core</value>
         <value>Spring-examples</value>
     </list>
    </property>
  
    <!-- Injecting 'references to other beans' as dependencies-->
    <property name="imagesInBlogAsList">
     <list>
         <ref bean="image1"/>
         <ref bean="image2"/>
         <ref bean="image3"/>
         <ref bean="image4"/>
         <ref bean="image4"/> <!-- Duplicates will be accepted in List-->
     </list>
    </property>



    <!-- Injecting 'primitive values'  in Set type property-->
    <property name="tagsAssignedAsSet">
     <set>
         <value>Java</value>
         <value>Java</value> <!-- Duplicates will not get accepted in Set-->
         <value>Spring</value>
         <value>Spring-core</value>
         <value>Spring-examples</value>
     </set>
    </property>
  
    <!-- Injecting 'references to other beans' as dependencies-->
    <property name="imagesInBlogAsSet">
     <set>
         <ref bean="image1"/>
         <ref bean="image2"/>
         <ref bean="image3"/>
         <ref bean="image4"/>
         <ref bean="image4"/>  <!-- Duplicates will not get accepted in Set-->
     </set>
    </property>
  
    <!-- Injecting values into an 'array' -->
    <property name="authors">
     <list>
         <value>Mr. X</value>
         <value>Mr. Y</value>
     </list>
    </property>

<!-- <set> Can also be used for 'authors' instead of <list> AS:

    <property name="authors">
     <set>
         <value>Mr. X</value>
         <value>Mr. Y</value>
     </set>
    </property>
  
    In case of <set>, duplicates in array 'authors' will not get accepted.
 -->
  
</bean>

</beans>


Step3: Add jars

Add the above mentioned jars in your project by right clicking on your project SpringDICollections,  go to Build Path > Configure Build Path > Add External JARs....

You can download commons-logging-1.1.1.jar from here. Spring related jars can be found in dist folder of your downloaded Spring 3.0.2 distribution folder.

Step 4: Running the program.

Right Click on the project SpringDICollections and go to Run As > Java Application.

You will see the following output  in the Console Pane.

Output:

Tags Assigned To Blog As List::
Java
Java       [Note the duplicates are allowed!]
Spring
Spring-core
Spring-examples
**************
Tags Assigned To Blog As Set::
Java    [Note the duplicates are NOT allowed!]
Spring
Spring-core
Spring-examples
**************
Images Used In Blog As List::
Image ID:image1
Image ID:image2
Image ID:image3
Image ID:image4
Image ID:image4   [Note the duplicates are allowed!]
**************
Images Used In Blog As Set::
Image ID:image1
Image ID:image2
Image ID:image3
Image ID:image4  [ [Note the duplicates are NOT allowed!]]
**************
Authors of Blog::
Mr. X
Mr. Y


Hope this would be helpful!



I would like to know your comments and if you liked the article then please share it on social networking buttons.


Dependency Injection into Map and Properties type properties.


This tutorial shows how to inject values into Map and java.util.Properties type properties of Spring beans.

This example is using following technologies:

1) Spring-framework-3.0.2.RELEASE
2) Eclipse Java EE IDE Helios Release (Eclipse version 3.6)
3) Java SE 6  

Jars Used:
 org.springframework.beans-3.0.2.RELEASE.jar
 org.springframework.core-3.0.2.RELEASE.jar
 org.springframework.context-3.0.2.RELEASE.jar
 org.springframework.asm-3.0.2.RELEASE.jar
 org.springframework.expression-3.0.2.RELEASE.jar
 commons-logging-1.1.1.jar


Step 1: Create a new Project in eclipse.


Create a new project in eclipse by going to File > New > Java Project and name it as SpringDIMap.

Project structure in eclipse is shown below:



There are four files used in this program:

1)      NewsLetterSubscriber.java
2)      NewsLetter.java
3)      MainApp.java
4)      ApplicationContext.java


Step2: Add the source code.


Add the following source code in eclipse.

NewsLetterSubscriber.java
package examples.spring.di;


import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

public class NewsLetterSubscriber {

Map<String,String> subscribersDetailsAsMap;
Map<String,NewsLetter> newsLetterToSend;

Properties subscribersDetailsAsProp;

public void setSubscribersDetailsAsMap(Map<String,String> subscribersDetailsAsMap){
this.subscribersDetailsAsMap=subscribersDetailsAsMap;
}

public Map<String,String> getSubscribersDetailsAsMap(){
return (Map<String,String>)subscribersDetailsAsMap;
}

public void setNewsLetterToSend(Map<String,NewsLetter> newsLetterToSend){
this.newsLetterToSend=newsLetterToSend;
}

public Map<String,NewsLetter> getNewsLetterToSend(){
return (Map<String,NewsLetter>)newsLetterToSend;
}


public void setSubscribersDetailsAsProp(Properties subscribersDetailsAsProp){
this.subscribersDetailsAsProp=subscribersDetailsAsProp;
}

public Properties getSubscribersDetailsAsProp(){
return subscribersDetailsAsProp;
}


public void showSubscriberDetails(){
System.out.println("News Letter Subscribers Details AS MAP:: ");

for(String key : subscribersDetailsAsMap.keySet()){
System.out.println("Name="+key+" Email="+subscribersDetailsAsMap.get(key));
}

System.out.println("**************");

System.out.println("News Letter Subscribers Details AS PROPERTIES:: ");
Iterator iter=subscribersDetailsAsProp.keySet().iterator();
while(iter.hasNext()){
     String key=(String)iter.next();
     System.out.println("Name="+key+" Email="+subscribersDetailsAsProp.getProperty(key));
 }
}

public void showNewsLetterDetails(){

   System.out.println("**************");
   System.out.println("News Letter Details:: ");

   for(String key : newsLetterToSend.keySet()){
   System.out.println("Subject="+key+" News Letter Id="+newsLetterToSend.get(key).getNewsLetterId()+" Author="+newsLetterToSend.get(key).getAuthor());
  }

 }

}


NewsLetter.java
package examples.spring.di;

public class NewsLetter {

String newsLetterId;
String author;

public void setNewsLetterId(String newsLetterId){
this.newsLetterId=newsLetterId;
}

public String getNewsLetterId() {
return newsLetterId;
}


public void setAuthor(String author){
this.author = author;
}

public String getAuthor() {
return author;
}

}


MainApp.java
package examples.spring.di;

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

public class MainApp {
public static void main(String args[]){
ApplicationContext ctx=new ClassPathXmlApplicationContext("resources/ApplicationContext.xml");
NewsLetterSubscriber newsLetter=(NewsLetterSubscriber)ctx.getBean("letterSubscriber");
newsLetter.showSubscriberDetails();
newsLetter.showNewsLetterDetails();
}

}



ApplicationContext.java
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="nLetter1" class="examples.spring.di.NewsLetter">
  <property name="newsLetterId" value="letter1"/>
  <property name="author" value="MR. A"/>
</bean>

<bean id="nLetter2" class="examples.spring.di.NewsLetter">
  <property name="newsLetterId" value="letter2"/>
  <property name="author" value="MR. B"/>
</bean>

<bean id="nLetter3" class="examples.spring.di.NewsLetter">
  <property name="newsLetterId" value="letter2"/>
  <property name="author" value="MR. X"/>
</bean>

<bean id="nLetter4" class="examples.spring.di.NewsLetter">
  <property name="newsLetterId" value="letter2"/>
  <property name="author" value="MR. Y"/>

</bean>


<bean id="letterSubscriber" class="examples.spring.di.NewsLetterSubscriber">

<!-- Injecting 'primitive values' in MAP type property-->
<property name="subscribersDetailsAsMap">
<map>
<entry key="John" value="John@dash.com"/>
<entry key="Sandy" value="Sandy@dash.com"/>
<entry key="Sandeep" value="Sandeep@dash.com"/>
<entry key="Joseph" value="Joseph@dash.com"/>
</map>
</property>

<!-- Injecting 'reference to other beans' in MAP type property-->
<property name="newsLetterToSend">
<map>
<!-- Note 'value-ref' instead of 'value'-->
<entry key="Core Java" value-ref="nLetter1"/>
<entry key="Spring" value-ref="nLetter2"/>
<entry key="Hibernate" value-ref="nLetter3"/>
<entry key="JEE" value-ref="nLetter4"/>
</map>
</property>



<!-- Injecting Dependencies in 'Properties' type property-->
<property name="subscribersDetailsAsProp">
<props>
<prop key="John">John@dash.com</prop>
<prop key="Sandy">Sandy@dash.com</prop>
<prop key="Sandeep">Sandeep@dash.com"</prop>
<prop key="Joseph">Joseph@dash.com"</prop>
</props>
</property>

</bean>

</beans>


Step3: Add jars
Add the above mentioned jars in your project by right clicking on your project SpringDIMap,  go to Build Path > Configure Build Path > Add External JARs....

You can download commons-logging-1.1.1.jar from here. Spring related jars can be found in dist folder of your downloaded Spring 3.0.2 distribution folder.

Step 4: Running the program.

Right Click on the project SpringDIMap and go to Run As > Java Application.

You will see the following output  in the Console Pane.

Output:
News Letter Subscribers Details AS MAP::
Name=John    Email=John@dash.com
Name=Sandy    Email=Sandy@dash.com
Name=Sandeep    Email=Sandeep@dash.com
Name=Joseph    Email=Joseph@dash.com
**************
News Letter Subscribers Details AS PROPERTIES::
Name=John          Email=John@dash.com
Name=Sandeep    Email=Sandeep@dash.com"
Name=Joseph      Email=Joseph@dash.com"
Name=Sandy       Email=Sandy@dash.com
**************
News Letter Details::
Subject=Core Java       News Letter Id=letter1     Author=MR. A
Subject=Spring             News Letter Id=letter2    Author=MR. B
Subject=Hibernate        News Letter Id=letter2    Author=MR. X
Subject=JEE                 News Letter Id=letter2    Author=MR. Y

Thanks!




I would like to know your comments and if you liked the article then please share it on social networking buttons.