When I started reading about Spring, one concept kept appearing : Inversion of Control (IoC). IoC is an apparently simple design pattern, but rather interesting. Here's a fast example of how it can be used:
Imagine you have class Foo and class Dummy. Class Foo has somewhere inside, the following lines:
...
Dummy dummy = new Dummy();
dummy.doSomething();
...
Pretty standard stuff :)
This example tells us one thing: there is a dependency between
Foo and
Dummy. Sometimes we don't want that....we need to use functionalities provided by
Dummy, but we don't want to be attached to the
Dummy implementation, because there could be several different implementations of
Dummy's functionality. And if wanted to use
Dummy2 implementation, we would have to change the code for
Foo. So, how do we make those two classes independent ? First, instead of using directly the
Dummy class we could use a java interface that publishes the functionality we want:
public interface Dummy {
public void doSomething();
}
And then, create an implementation for it:
public class DummyImpl implements Dummy {
public void doSomething(){
...
}
}
And in the
Foo class we could have:
Dummy dummy = new DumyImpl();
dummy.doSomething();
Now, we call mehods from the interface instead of directly from the implementing class. This is good, but not enough...We still have "...new DummyImpl()" in there. So the dependency isn't gone yet. To get rid of the dependency we can't instantiate the
DummyImpl inside
Foo. Instead we could have a setter method in
Foo that receives an already instantied implementation of
Dummy:
...
Dummy d;
public void setDummy(Dummy d){
dummy = d;
}
...
Now
Foo is completely independent of any
Dummy implementation. But if we don't instantiate
Dummy inside
Foo, we need to instantiate it somewhere. Or maybe not....that's where a
Component Container comes in: it will instantiate it for us :)
In Spring we can define, in a XML file, the classes that we need to use, along with their dependencies. So if we run our little example trough Spring, we would have to specify the
Foo class, the
Dummy implementation and their dependency. Next, when we need an instance of
Foo, we ask it from Spring. It will then instantiate
Foo, instantiate
Dummy and call
setDummy() on the
Foo class. Only then it returns to us an instance of
Foo. This is great if we want to change the
Dummy implementation: we only need to change the name of the class implementing
Dummy, in the XML file. You can read the
Spring reference manual for a detailed explanation of how to use this.
There are other Component Containers besides Spring, namely the
Pico Containter (note: Spring provides a lot more than just a Component Container). I haven't studied them, though...
You can have a more in-depth (and plain better) explanation of what is Inversion of Control (also called Dependency Injection) in
this article.