This might be a naive question. I'm currently learning the Spring framework and dependency injection. 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.
Consider the following:
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");
}
}
Then you could simply do:
Saw saw = new HandSaw();
SawMill sawMill = new SawMill();
sawMill.setSaw(saw);
sawMill.run();
Which would be equivalent to:
<bean id="saw" class="HandSaw"/>
<bean id="sawMill" class="SawMill">
<property name="saw" ref="saw"/>
</bean>
plus:
ApplicationContext context = new ClassPathXmlApplicationContext("sawmill.xml");
SawMill springSawMill = (SawMill)context.getBean("sawMill");
springSawMill.run();
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?
(I know the Spring framework is more than that, but I'm thinking of the need for a DI container.)
In the first example it would also be trivial to change dependencies midstream:
// gotta chop it faster
saw = new ChainSaw();
sawMill.setSaw(saw);
sawMill.run();