Simple Spring Application Develop Step-by-Step

Learning Spring Application Dependency Injection – Constructor & Setter

Note: Before going into the details, it is advised to go through Introduction to Java Spring Framework

Dependency injection injects (carries) dependencies (variable values) into our Java application (from XML file). Is it confusing? Of course a lot, it’s very simple when you do understand (I explain in my own style). In general, we declare variables and give values to them (say from keyboard) in a Java program and use them or utmost, one Java class variables values can be used by other Java class. But in Spring, variables are declared in Java class but values are given in a XML file. A client program reads the values from the XML file and puts them in bean code and executes. Java class depends (this is what is dependency) for the values on a XML file. The Spring container actually injects these dependencies (variables values) when a bean object is created. The advantage of dependency injection (IoC) is the code gets cleaner and gets decoupled to a higher level as bean does not search for their dependencies (variable values) where the bean is located or to say in its code (Service Locator pattern).

The variable values, from XML file, can be injected (read) into the Java class in two ways – using a constructor or setter methods. That is, two Dependency Injection styles exist.

  1. Constructor Dependency Injection: Dependencies are provided (injected) with constructors of the component (bean).
  2. Setter Dependency Injection: Dependencies are provided with setter methods. It is mostly preferred to constructor dependency injection.

Following application uses both the above. It contains three programs:, applicationContext.xml file and client program.

Simple Spring Application

1. Spring Application Bean Program:

A bean object is a POJO (Plain Old Java Object). POJO is a Java object that doesn’t extend or implement some specialized (user defined) classes and interfaces. All normal Java objects are POJO.

Spring bean does not contain getter methods; instead, it can have its own printing methods. The bean has variables declaration, constructor and setter methods and also a few methods to print the values. The values for the variables are given in next XML file.

import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

public class A  
                                  // variables are known as dependent objects of our class
  private int i;
  private double d;
  private String myStr;
  private Date myDate;
  private List myList;
  private Properties myProp;

  public A() 		          // default constructor

                                  // this overloaded constructor is used later to inject variables in client program
  public A(int i, double d, String myStr, Date myDate, List myList, Properties myProp) 
    this.i = i;
    this.d = d;
    this. myStr = myStr;
    this. myDate = myDate;
    this. myList = myList;
    this. myProp = myProp;
  }			          // setter methods to inject variables in the client program
  public void setI(int i) 
    this.i = i;
  public void setD(double d) 
    this.d = d;
  public void setMyStr(String myStr) 
    this.myStr = myStr;
  public void setMyDate(Date myDate) 
    this.myDate = myDate;
  public void setMyList(List myList) 
    this.myList = myList;
  public void setMyProp(Properties myProp) 
    this.myProp = myProp;
                                  // two printing methods to print the values in client program
  public void printPrimitives() 

  public void printSecondaries() 
    Iterator i = myList.iterator();

    Enumeration en = myProp.propertyNames();
      String name = en.nextElement().toString();
      String value = myProp.getProperty(name);
      System.out.println(name +" " + value);
                                  // one more user-defined method to use a variable in client program
  public int getMe() 
    return i;

Program is self explanatory. I included one extra method getMe() to get the value of i in client program and use i in some arithmetic operation; else you can write one getter method for i. The printXXX() methods in the code are used just to print the values of variables.

2. Spring Application applicationContext.xml (where variables of are given values)

In this XML file, objects of class A are created and given values. The file is loaded by the container on the fly. Even though the name is given as applicationContext.xml (it is the default name given by the container, if you ask the container to create one for you), infact, it can be any one and the most commonly used names are spring.xml and beans.xml etc.







In this XML file both constructor and setter injections are given (instead of writing two different XML files). Observe how the values are given to variables List and Properties.

<beans> is the root tag for the whole XML file. All the Java API classes (of course user-defined also) like Date, Calendar etc. should be declared with "bean" tag with an id attribute. This id value is used later in the code to refer Date class.


Here class="A" refers id is a1. a1 is nothing but an object of A (this is how an object of bean is created). This a1 is used later in the client program. In case of constructor injection, the above statement becomes internally as A a1 = new A(45, 88.88, …..) and the values of the constructor parameters 45 and 88.88 etc. are assigned to instance variables of the bean.

The first refers the first parameter in the constructor. It is i variable of bean Similarly, the next refers the second parameter and is d variable. Order should be maintained. Else one variable goes to another and finally program does not compile or gives wrong results.


Here, as in the previous case, a2 is the object of class A. Internally container calls as A a2 = new A() and creates a2 object. As it is a setters injection, values for a2 object are assigned by calling a2.setI(56) and a2.setD(99.99) etc.

Observe how the parameters List and Properties are given values. <props> indicates Properties data structure and indicates each property of Properties class. With setter injection, the values given to variables can be in any order because variable names are also given along with values.

Note: The name of the XML file can be anyone like spring.xml or beans.xml etc.

3. Spring Application Client Program:

import org.springframework.context.ApplicationContext;

public class Client 
  public static void main(String rags[]) throws Exception 
    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

    A mine = (A) ac.getBean("a1");

    A yours = (A) ac.getBean("a2");

    int k = mine.getMe();
    System.out.println("Cube of " + k + " is " + Math.pow(k,3));

a1 and a2 are the objects of class A declared in XML file with id attribute. The parameter of getBean() method of ApplicationContext (given in the above client program) should be these objects only.

MyEclipse console screen when the above Spring Application client program is run.

Spring Application

9 thoughts on “Simple Spring Application Develop Step-by-Step”

  1. Sir, How can we limit Heap Size in spring mvc. I have created war file and uploaded in on server but it is not allowing as they that its heap size is growing more than 128mb.. so is there any step or configuration that i can limit

  2. I studied about the Dependency Injection on most of the famous websites from long time but always my interest gone too far but after using this website really its awesome for me……..sir i appreciate you always to maintain this blog as it is. and try to maintain the blog about web-services ..i always used your website to understand anything in java.
    Thanks to make me understand…..

  3. Rupesh Vislawath

    Hello Sir,
    Couldn’t find simpler explanation than this,simply flawless :)
    1 query regarding Constructor based DI, why are we writing super() in each Constructor…?

    And why Setter based DI is preferred more than Constructor based DI?

  4. Java class depends (this is what is dependency) for the values on a XML file.

    Sir, here “Java class” refers to Bean program or client program…?

Leave a Comment

Your email address will not be published.