Monday, June 23, 2008

IoC (Inversion Of Control) and Dependency injection (DI)


Introduction:

Lots of us hear this word and also hear that this container is using IoC (inversion of control) so what is it all about and what does this mean? we will be working using Spring IoC through this article so lets start by checking the formal definition of the Dependency injection:“Dependency injection (DI) in Computer programming refers to the process of supplying an external dependency to a software component. It is a specific form of inversion of control where the concern being inverted is the process of obtaining the needed dependency.”Ho ho sounds little bit confusing, so lets make it more simple so first we need to know what is IoC and what is DI .Well we can say that IoC is a generic term and the DI is a more specific term so this mean that Dependency injection is more specific term than the IoC but still don't understand the IoC thing.

Life Without IoC and DI

In a standard component container,the component themselves ask the container for the resources they want for example lets check this segment of code (which you can find in most of EE application):

Context context=new InitialContext();
DataSoruce dataSource=(DataSource)context.lookup("jdbc/TestingDS");
Connection connection=dataSource.getConnection("yourUser","yourPassword");
Statement statement=connection.CreateStatment();
ResultSet results=statement.executeQuery("select * from users");
.
.
. //i didnt include all the code just the important thing

so in the above code we just initialize a context (JNDI)
and perform a lookup for a resource bounded at jdbc/TestingDS and then get the results and cast it as a DataSource after that we use it and continue with our processing.

oh yea so every time i want to do so i will have to make the lookup thingy to get the data source or any resource i might need.
mmm so i will keep asking my container to give me what i want? yup you will.
well lets see how would the container and the component interact with each other (without IOC)

A Day in the Container's Life !

Component: Hi Mr.Container.
Container:Hi Component.

Component:how is your day?
Container :oh i have been busy serving all other components and don't have time for myself :( .

Component:oh poor you Mr.Component.
Container:ahh what can i do this is my job :) , so how can i serve you ?
Component :oh yea i forgot , i want to you to serve me the resource bounded at bla bla bla
Container:ok sure no problem, just a min. here you are (hehehe now we got what we want :D )
Component:oh many thanks MR.Container, have a nice day.
Container:you too component bye.

so in here as we can see the component keeps asking the container to provide the needed resources.

Hollywood and IoC:

IoC as most of people say it apples Hollywood principle which is :

Component: Hello Mr.Container !Container :don't call Me, I will call you.TEET TEET TEET (the container hanged the phone :S )
Component : Shocked :|

This is what they call: don't call us , we will call you principle.

yup it is what you are thinking in , yes the container will take control over the resources for the
component but without involving the component in that, in other words the control of the resource will be inverted from component to container and its configuration(through XML as most of people do and as i do)


Life With IoC:


what if we want to apply IoC on the previous example?

Ok, so we will just need to modify some stuff (adding a property for the DataSource and also using spring framework)

//class that contains the code for spring IOC
private DataSource dataSource;

public void setDataSource(DataSource ds)
{
dataSource=da;
}

public static void man(String[] args)
{
//so now dataSource is set by Spring IOC
Connection connection=dataSource.getConnection("yourUser","yourPassword");
Statement statement=connection.CreateStatment();
ResultSet results=statement.executeQuery("select * from users");
. . . //i didnt include all the code just the important thing
}

//segments from XML configuration file

<%bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<%property name="driverClassName" value="youDriverClassName" />

<%property name="url" value="DBUrl" />

<%property name="username" value="yourUsername" />

<%property name="password" value="youPassword" />

<%bean name"ourComponent" class="com.springIoC.IoCTesting">

<%property name="dataSource" ref="dataSource">

<%/bean>


as we can see in the above XML we just stated that we have a bean from class bla bla which has a property named dataSource so spring IoC will just think like that :

mmm (spring IoC thinking...)
oh yea i have a bean named ourComponent .
wait a minute this bean have a property named dataSource! .
this property refers to another bean named dataSource which have some property (url,username,password,driverclassname) .
oh great so now what i need to do is inject this bean property (data source property in the ourComponent ) with the Datasource ,TA DA now it is done.

so we can see here that we didn't make any lookup , so there is zero times component did ask the container about the DataSource.
in this case the control over deciding which DataSource to use is in the container not the component so once the container gets a DataSource it will pass it to the component by calling the setter (SetDataSource).when spring IoC container loads at runtime it will inject the dependency into our component (this is done at runtime by XML configuration as we can see above) so the Data Source will be injected into ourComponent and now we can make anything with this data source (with zero component to container call).

below is a diagram that shows the interaction in case we are using IoC or non IoC Container.

in the first we can see that the component ask the container to provide the resource it need (data source in our case ) but in the second image the container creates and inject the resource into the component



























Types Of Injection:
We have seen in the previous sample that spring do the injection through setter (property) thats one way of injection , another way it to inject through the constructor (which spring also support)
this mean that i can inject all resource in the component through a constructor (and that constructor takes all the needed resource through arguments supplied)


so now we know what is Dependency injection and also the IoC concept , there are also some IoC containers other than spring IoC container for example :Pico container and also Avalon framework

7 comments:

Ravi said...

this is a good article.

Ahmed Ali said...

Ravi,

Tahnks for your comment, glad you liked it :)

Anonymous said...

This is very good , simple Crispy explanation for IOC, please do post this kind on articles....

Ahmed Ali said...

Hi,

glad you enjoyed it , stay tuned and i will post more articles :)

Thanks,
Ahmed

Anonymous said...

Hi ,
Can I have similar kind of article on "spring proxy" concept in simple way ?
or
Can you share some good simpile link ?

With hopes.
Thanks.

Ahmed Ali said...

Hello,

Sorry for my late respons but i just saw you comment now , as for your request i will make a post to talk about Spring AOP and Proxy
and sorry again for not reading your comment earlier :)

Thanks

Anonymous said...

Bonjorno, javalandscape.blogspot.com!
[url=http://viagragent.pun.pl/ ]Comprare viagra online[/url] [url=http://cialishols.pun.pl/ ]Compra cialis in Italia[/url] [url=http://viagratetb.pun.pl/ ]Acquisto viagra online[/url] [url=http://cialisiall.pun.pl/ ]Acquistare cialis generico[/url] [url=http://viagraradj.pun.pl/ ]Compra viagra [/url] [url=http://cialisantr.pun.pl/ ]Acquisto cialis online[/url]