Tuesday, June 17, 2008

Spring : Inversion of Control (IoC) / Dependency Injection (DI)

We have heard a lot about Spring in recent years. Specially it is one of an indespensable tool widely employed by Java developers. It has a kind of defacto standard as a container. Though Spring has lot of features to delve into, I am specially talking about the inversion of control and dependency injection in this blog. Here I am trying to define inversion of control/ dependency injection because what I found over the years is that eventhough developers are using IOC and DI they are little aware of what actually they mean. Though nobody needs a precise definition to use the features, I believe understanding them would be better.

Dependency Injection (DI) and Inversion of Control (IoC) are interchangable terms but I am going to define them from Injection and Control perspective. For example look at the class below:-


public class UserManager {
private UserDao userDao;

// code involving useDao

public void setUserDao(UserDao userDao){
this.userDao=userDao;
}

}


Lets assume that userDao is a spring bean injected into UserManager (I am assuming some familiarity with spring because I just want to make concepts of DI and IoC clear). Now interpret it this way: UserManager is dependent on UserDao for some operation> In traditional programming we might create the UserDao instance for use in UserManager like this UserDao userDao=new UserDao() but not as such with Spring. The UserManager is not responsible for creating the dependency that it requires itself but rather depends on Spring to inject its dependency.
Hence the name Dependency Injection.

Now for IoC, see it this way: the control of creating the object necessary for UserManager has been transferred to Spring. The control that traditional objects use to have has been lost and control has inversed. The owner uses the object created by something else. Hence the name Inversion of Control.

No comments: