title: Understanding the need for a DI framework
body: <p>This might be a naive question. I'm currently learning the Spring framework and <i>dependency injection</i>. While the basic principle of DI is rather easy to grasp, it's not immediately obvious why you need an elaborate framework to implement it.</p>
  
  <p>Consider the following:</p>
  
  <pre><code>public abstract class Saw
  {
      public abstract void cut(String wood);
  }
  
  public class HandSaw extends Saw
  {
      public void cut(String wood)
      {
          // chop it up
      }
  }
  
  public class ChainSaw extends Saw
  {
      public void cut(String wood)
      {
          // chop it a lot faster
      }
  }
  
  public class SawMill
  {
      private Saw saw;
  
      public void setSaw(Saw saw)
      {
          this.saw = saw;
      }
  
      public void run(String wood)
      {
          saw.cut("some wood");
      }
  }
  </code></pre>
  
  <p>Then you could simply do:</p>
  
  <pre><code>Saw saw = new HandSaw();
  SawMill sawMill = new SawMill();
  sawMill.setSaw(saw);
  sawMill.run();
  </code></pre>
  
  <p>Which would be equivalent to:</p>
  
  <pre><code>&lt;bean id="saw" class="HandSaw"/&gt;
  
  &lt;bean id="sawMill" class="SawMill"&gt;
     &lt;property name="saw" ref="saw"/&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>plus:</p>
  
  <pre><code>ApplicationContext context = new ClassPathXmlApplicationContext("sawmill.xml");
  SawMill springSawMill = (SawMill)context.getBean("sawMill");
  springSawMill.run();
  </code></pre>
  
  <p>Granted, this is a contrieved example, and with more complex object relationships it might be more efficient to stash up an XML file than writing it programmatically, but surely there must be more to it than that?</p>
  
  <p>(I know the Spring framework is more than that, but I'm thinking of the need for a DI container.)</p>
  
  <p>In the first example it would also be trivial to change dependencies midstream:</p>
  
  <pre><code>// gotta chop it faster
  saw = new ChainSaw();
  sawMill.setSaw(saw);
  sawMill.run();
  </code></pre>