Thursday, October 16, 2008

Inversion of Control (IoC) and Dependency Injection (DI) paradigms

Came across this very good explanation of Inversion of Control (IoC) and Dependency Injection (DI) paradigms. Thought I would make a note of it:
(click here for the complete article on Java Dev Journal)

The analogy people most often make when talking about IoC is called the Hollywood principle: "Don't call me, I'll call you." What this means is that you don't call the framework code, but the framework calls certain methods on your components. This isn't something new, for instance, when you look at the servlet interface, you can see that you must implement the init and destroy methods. These methods are called from the servlet container on startup and shutdown of your servlet. This concept is also used in Spring, among other things, for specifying which methods to call on construction and destruction of your POJO.


Besides IoC, another important concept to understand is Dependency Injection (DI). This term was coined by Martin Fowler and describes a pattern of how to perform wiring between beans. This means that any dependencies your POJO might have are injected into your component, instead of you having to retrieve them. In J2EE (at least until 1.5) when you required a resource (a data source, another bean, etc.) you had to use JNDI to pull that resource in. With DI you don't have to do that anymore. With DI your container will make sure you have the dependency pushed into your POJO using getters and setters. In the new J2EE specs much of the same concepts are used.

No comments: