Search code examples
dependency-injectionframeworksinversion-of-control

Spring Philosophy


Everytime I ask anyone what the Spring Framework is or what it does, they simply say to me, you remember that Hollywood principle right "Don't call me, I will call you", that's exactly what Spring Framework does.

What should I make out of this?


Solution

  • It means that a class doesn't manually instantiate the components that it depends on -- something (such as Spring's IoC context) gives the class an instance of each component that it needs. This is usually done either via setters for each component, or a constructor that takes all those components.

    Basically instead of a class doing manual instantiation by itself:

    public class Foo {
      private Bar bar;
      public void doStuff() {
        bar = new BarImplementation();
        bar.doMoreStuff();
      }
    }
    

    IoC injects the dependency Bar into Foo, so that when you get a Foo object from the context, you know it's ready to use.

    public class Foo {
      private Bar bar;
      public void setBar(Bar bar) { this.bar = bar; }
      public void doStuff() {
        // bar's already been set by the time this is called!
        bar.doMoreStuff();
      }
    }
    

    You didn't manually instantiate Bar, instead your configuration files (such as Spring XML) set it for you. Additionally, Foo is no longer tied to BarImplementation. Using interfaces allows you to insert different implementations, including mocks used for testing.