Showing posts with label Dependency Injection. Show all posts
Showing posts with label Dependency Injection. Show all posts

Dependency Injection with Java Spring IoC, A Complete Example

Here i am going to describe a simple example of Dependency Injection which uses Spring IoC framework.
You may refer to my earlier"Understanding Dependency Injection and Its Importance" for understanding the concepts.
This example uses Implementation of  Operation, Reader and Writer Interfaces.
We simply perform a one of the arithmentic Operation by taking values from Reader and write the values using Writer Class.

Reader Interface:
public interface Reader {
    Operands readValues(String promptMsg);

Its implementations can be:
public class ConsoleReader implements Reader{
    Operands oprnds;
    Scanner sc;
    public ConsoleReader (){
        oprnds=new Operands();
        sc=new Scanner(;
    public Operands readValues(String promptMsg) {
        return oprnds;

The Operation Interface
public interface Operation {
    Result operate(long op1,long op2);
    String getOperationName();

The Operation Interface can have implementations such as
public class Multiply implements Operation {
    Result res;
    public Multiply(){
          res=new Result();
    public Result operate(long op1, long op2) {
        return res;
    public String getOperationName() {
        return "Multiply";

public class Add implements Operation {
    Result res;
    public Add(){
        res=new Result();
    public Result operate(long op1, long op2) {
        return res;
    public String getOperationName() {
        return "Add";

The  writer Interface
public interface Writer {
    void write(Result res);

Its ConsoleWriter Implementation
public class ConsoleWriter implements Writer{
 public void write(Result res){
    System.out.println("The result after operation : "+res.getRes());

Its TXTFileWriter Implementation
public class TXTFileWriter implements Writer{
    File file;
    PrintWriter fwriter;
    public TXTFileWriter(){
        try {
           file = new File("output.txt");
           fwriter = new PrintWriter( new BufferedWriter( new FileWriter(file)));
       } catch (Exception ex) {
    public void write(Result res)

The Model Classes
public class Operands {
    private long op1;
    private long op2;
//setters and getters

The Result Class
public class Result {
    private long res;
    //setters and getters

Now create a configuration file in class path i.e, src folder of project directory - confBean.xml.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
<bean id="operation" class=""/>
<bean id="reader" class=""/>
<bean id="writer" class=""/>

The dependency injection will help you to inject the implementations of an object at runtime.
In the Main Class: read the xml file and inject the dependent beans…
public class Main {
    public static void main(String[] args) {
    ApplicationContext ctx = 
new ClassPathXmlApplicationContext("confBean.xml");
        //get beans from ctx
        Reader rdr = (Reader) ctx.getBean("reader");
        Operation opr = (Operation)ctx.getBean("operation");
        Writer wrt = (Writer) ctx.getBean("writer");//
        //read operands
        Operands opnds = rdr.readValues("Enter the Values :");
        //do operation
        Result res =opr.operate(opnds.getOp1(), opnds.getOp2());
        //write result

Dependency Injection in Java without Spring IoC Framework........ How it is possible... A Simple way

You can first read Understanding Dependency Injection and its Importance, before this post for clearing Funda of Dependency Injection.
How can we this do programmatically.
  • Create a interface Wheel.
    Interface Wheel(){
  • Create implementations
    class ChineseRubberWheel implements Wheel{
         //override and define
    class NepaleseRubberWheel implements Wheel{
         //override and define
  • Create a txt file, where you write the valid name(say NepaleseRubberWheel ) of a Implementation of Wheel
  • Read the txt file
  • And finally, to Dynamically load the NepaleseRubberWheel as instance of Wheel;
    String wheeltoInject = ReadFromTXTFile();
    // Create Wheel object
    Wheel wheelToRun =(Wheel)     (Class.forName(wheelToInject).newInstance());
    // Execute methods of the wheel object.

This works for any implementation of Wheel. To change the Wheel on the Car just change name of Implementation on the txt file.

Understanding Dependency Injection and its Importance, A tutorial

Understanding Dependency Injection and its Importance

Any application is composed of many objects that collaborate with each other to perform some useful stuff. Traditionally each object is responsible for obtaining its own references to the dependent objects (dependencies) it collaborate with. This leads to highly coupled classes and hard-to-test code.

For example, consider a `Car` object.

A `Car` depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the `Car` object.

Without Dependency Injection (DI):

  class Car{  
    private Wheel wh = new NepaliRubberWheel();  
    private Battery bt = new ExcideBattery();  
    //The rest  

Here, the `Car` object *is responsible for creating the dependent objects.*

What if we want to change the type of its dependent object - say `Wheel` - after the initial `NepaliRubberWheel()` punctures?
We need to recreate the Car object with its new dependency say `ChineseRubberWheel()`, but only the `Car` manufacturer can do that.

 Then what does the `Dependency Injection` do for us...?

When using dependency injection, objects are given their dependencies *at run time rather than compile time (car manufacturing time)*.
So that we can now change the `Wheel` whenever we want. Here, the `dependency` (`wheel`) can be injected into `Car` at run time.

After using dependency injection:

Here, we are **injecting** the **dependencies** (Wheel and Battery) at runtime. Hence the term : *Dependency Injection.* We normally rely on DI frameworks such as Spring, Guice, Weld to create the dependencies and inject where needed.

   class Car{  
    private Wheel wh; // Inject an Instance of Wheel (dependency of car) at runtime  
    private Battery bt; // Inject an Instance of Battery (dependency of car) at runtime  
    Car(Wheel wh,Battery bt) {  
      this.wh = wh; = bt;  
    //Or we can have setters  
    void setWheel(Wheel wh) {  
      this.wh = wh;  

The advantages/benefits of dependency injection are:

  • decoupling the creation of an object (in another word, separate usage from the creation of object)
  • ability to replace dependencies (eg: Wheel, Battery) without changing the class that uses it(Car)
  • promotes "Code to interface not to an implementation" principle
  • ability to create and use mock dependency during a test (if we want to use a Mock of Wheel during test instead of a real instance.. we can create Mock Wheel object and let DI framework inject to Car)