Dependency Injection in Spring

Dependency Injection (DI): is a way to let the framework or the container work out the complexities of service instantiation, initialization and sequencing and supplies the service references to the clients as required. In spring IOC container has the responsibility of doing DI.


Consider a simple example:


public interface Vehicle {

                 void displayData();



A FourWheeler class implements Vehicle interface.


public class FourWheeler implements Vehicle {


      private String name;

      private int purchaseValue;

      private int noOfTyres;

      public FourWheeler(){}                          // default constructor                   

public FourWheeler(String name, int purchaseValue, int noOfTyres) {


   = name;

            this.purchaseValue = purchaseValue;

            this.noOfTyres = noOfTyres;


      public void displayData() {

            System.out.println(” Name of vehicle is “+ name);

            System.out.println(“Purchase Value is “ +purchaseValue);

            System.out.println(“Tyres the vehicle has “ +noOfTyres);


      public String getName() {

            return name;


      public void setName(String name) {

   = name;


      public int getPurchaseValue() {

            return purchaseValue;


      public void setPurchaseValue(int purchaseValue) {

            this.purchaseValue = purchaseValue;


      public int getNoOfTyres() {

            return noOfTyres;


      public void setNoOfTyres(int noOfTyres) {

            this.noOfTyres = noOfTyres;




The different ways in which the class can be instantiated using DI in spring.xml:


1) Setter based injection: The values of the properties of the class are set with the help of setter. Each class needs to declare the setter of the properties and their values are set from the spring configuration file.


 <?xml version=“1.0” encoding=“UTF-8”?>



       <bean id=“fourWheeler” class=“com.src.FourWheeler”> 

            <property name=“noOfTyres”> <value>4</value>



<property name=“name” value=“Honda”/>                                  

<property name=“purchaseValue” value=“900000”/>  




In above example the setter methods are created for noOfTyres, name, purchaseValue in FourWheeler  class and the values are set using <property> <value> tag in xml file.

Note that for each property the value is set using a different syntax. All syntaxes are valid and

can be used depending on the programmer liking. In this declaration the default constructor of class is called.


2)  Constructor Based injection: In this case the values are set using constructor of the java class. The call to constructor is made from the xml file using <constructor-arg>.  For the above mentioned java class constructor injection will be:


<?xml version=“1.0” encoding=“UTF-8”?>


<beans >      


      <bean id=“fourWheeler” class=“com.src.FourWheeler”> 

                        <constructor-arg> index=“0” value=“Honda”/>

                        <constructor-arg type=“Integer”>







In the above example the values to the bean is passed using <constructor-arg>. The sequence in which the parameters are passed should match with the constructor available in the class.


3) Static factory method: In the less common case where the container invokes a static, factory method on a class to create the bean, the class property specifies the actual class containing the static factory method that is to be invoked to create the object (the type of the object returned from the invocation of the static factory method may be the same class or another class entirely.


Consider the following method present in FourWheeler class:

public static TwoWheeler createInstance(){

            return new TwoWheeler();



Note that the method has to be static. And following line of code in xml:


<bean id=“twoWheeler” class=“com.src.FourWheeler” factory-method=“createInstance”/>


After execution of the above line twoWheleler bean will represent the TwoWheeler object which is created by calling the function from FourWheeler Class. The attribute factory-method tells which method to call present in the class mentioned. This scenario could possibly use in cases where Factory pattern is required.


4) Instance Factory method: In this case instead of having a static method a non-static method is present to create the object.


Consider the following method present in FourWheeler class:

public TwoWheeler createInstance(){

            return new TwoWheeler();



Note that the method need not be static. And following line of code in xml:


<bean id=“parentfourWheeler” class=“com.src.FourWheeler”/>


<bean id=“fourWheeler” factory-bean = “parentFourWheeler” factory-method=“createInstance” />


Here the twoWheeler object is created from a non-static method of class FourWheeler.

Introduction to Spring Part II – Bean, BeanFactory, ApplicationContext, IOC

In this technoticle I will be explaining some of the basic concepts of Spring :

Bean – It is the basic element of the framework. It is equivalent to an object created in java. In spring bean can be created using following methods:

1)      Setter injection

2)      Constructor injection

3)      Interface injection

4)      Static factory method

5)      Instance method

The detailed explanation is Dependency Injection

BeanFactory – As the name suggest the beanfactory instantiate, configure and manages all beans defined. These beans typically collaborate with one another, and thus have dependencies between themselves. The ways by which beanFactory can be created: 

  • InputStream is = new FileInputStream(“beans.xml
    XmlBeanFactory factory = new XmlBeanFactory(is);

  • ClassPathResource res = new ClassPathResource(“beans.xml”); 
    XmlBeanFactory factory = new XmlBeanFactory(res);

  • ClassPathXmlApplicationContext appContext =  new ClassPathXmlApplicationContext (new String[] { “applicationContext.xml”,”applicationContext-part2.xml”}
    BeanFactory factory = (BeanFactory) appContext;

When any of the above lines are executed all beans present in the “configuration” file(s) are instantiated and stored in the bean factory.Once the bean factory is loaded the bean can be retrieved:


   BeanClassName beanObj = (BeanClassName) factory.getBean(“beanName”);


ApplicationContext: ApplicationContext extends BeanFactory and thus provide extra functionality than BeanFactory.

The following are the additional functionalities:

·         MessageSource, providing access to messages in, i18n-style

·         Access to resources, such as URLs and files

·         Event propagation to beans implementing the ApplicationListener interface

·         Loading of multiple (hierarchical) contexts, allowing each to be focused on one particular layer, for example the web layer of an application

Invresion of Control – Earlier the control of interface was with the application program. For example it a typical user input application a prompt will pop up saying ‘Enter Name’ or at some place the property has to be set explicitly using the setter methods. But with the advent of IOC, now it’s the responsibility of the container in which beans are loaded to find the correct value of a property with the help of spring configuration file and now not much responsibility is left to the application program to set or get the values.IOC is too generic term, so spring generally designates it as Dependency Injection (DI). 

 A typical IOC container would look like:

IOC Container
IOC Container


  • An IOC can have multiple ApplicationContexts.
  • ApplicationContext can also refer other application context.
  • Applicationcontext can contain another applicationcontext.
  • Multiple beanfactories can be inserted in an applicationcontext.