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:
ConsoleReader:
public class ConsoleReader implements Reader{
    Operands oprnds;
    Scanner sc;
    public ConsoleReader (){
        oprnds=new Operands();
        sc=new Scanner(System.in);
    }
    public Operands readValues(String promptMsg) {
        System.out.println(promptMsg);
        oprnds.setOp1(sc.nextLong());
        oprnds.setOp2(sc.nextLong());
        return oprnds;
    }
}


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


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

Addition
public class Add implements Operation {
    Result res;
    public Add(){
        res=new Result();
    }
    public Result operate(long op1, long op2) {
        res.setRes(op1+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) {
           System.err.println(ex);
        }
    }
    public void write(Result res)
  {
     fwriter.println(res.getRes());
     fwriter.close();
    }
}


The Model Classes
Operands
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="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="operation" class="com.gt.spring.operation.Add"/>
<bean id="reader" class="com.gt.spring.reader.ConsoleReader"/>
<bean id="writer" class="com.gt.spring.writer.ConsoleWriter"/>
<beans>

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
        wrt.write(res);
    }
}


No comments :

Post a Comment

Your Comment and Question will help to make this blog better...