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(){
         rotate();
         applyBreak();
    }
  • 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.
    wheelToRun.rotate();
    wheelToRun.applyBreak();


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

No comments :

Post a Comment

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