Friday, April 24th, 2009

Spring’s Dependency Injection

If you are into Java enterprise application development, then get yourself ready to hear the terms ‘Spring‘, ‘Dependency Injection‘ or ‘IoC‘ a lot. Because, without these terms (and technologies) enterprise development wouldn’t be this much simpler. Spring, the framework which became very popular because of it’s capability to inject the dependencies to our Java objects in a very efficient manner. Spring’s lightweight dependency injection container manages all the defined beans and their dependencies.

So, what is this ‘dependency injection’ thing ?

Dependency Injection (or DI, in short) is nothing but the dependencies of your Java objects are managed by a container so that your object can concentrate on it’s functionality rather than searching for it’s dependencies. Here, it’s the container’s (for example Spring’s container) responsibility to inject all the dependent objects that your class need. You just need to tell the container what you want and the container takes care of the rest.

Confusing, huh !?

A Ground-breaking(!) HelloWorld2 App:

Let’s take a simple example – a Web2.0 hello world – ‘HelloWorld2′. You are writing a ‘HelloWorld2′ class which has the capability to tweet the message you are giving. From this, it is clear that your ‘HelloWorld2′ will need a TwitterService object to complete it’s task. So, usually you will declare a TwitterService variable in your ‘HelloWorld2′ class and you will instantiate a new ‘TwitterService’ object. The ‘HelloWorld2′ may look like this:

class HelloWorld2
{
	TwitterService ts = new TwitterService();

	public void sayHello(String name)
	{
		ts.tweet("Hello " + name);
	}
}

In the above, you are declaring and instantiating the TwitterService object in your HelloWorld2 code itself. In other words, your code is responsible for getting it’s dependent objects, in this case the TwitterService object.

Let’s see a different version of HelloWorld2.

The ‘Dependency Injected’ version of ‘HelloWorld2′:

Now, have a look at this code.

class HelloWorld2
{
	TwitterService ts = null;

	public void setTs(TwitterService ts){
		this.ts = ts;
	}

	public void sayHello(String name)
	{
		ts.tweet("Hello " + name);
	}
}

What’s new in this version?! We’ve removed the TwitterService object creation, instead created a new setter method setTs() (I know, it’s a bad name!). But, where is our mission-critical TwitterService object is getting created?

That’s where the dependency Injection comes into play. The creation of objects will be outsourced to the container. Let’s outsource this task to the Spring container using a Spring configuration file.

<beans>
...
	<bean id="twitterService" class="foo.TwitterService" />
	...
	<bean id="helloWorld" class="bar.HelloWorld2">
		<property name="ts" ref="twitterService" />
	</bean>
...
</beans>

In the above configuration file, we are defining the TwitterService as a Spring managed bean and then, in the ‘helloWorld’ bean definition, we are telling the Spring container to inject ‘twitterService’ bean for the property ‘ts’. When the Spring container reads this XML file, it will create the ‘helloWorld’ bean and using the setter method for the variable ‘ts’, it will inject the ‘twitterService’ into ‘helloWorld’ . This technique is called as setter method injection(duh!).

Apart from this XML based configuration, Spring supports annotations based DI configuration also. I’ll be explaining that in my next article.

{ 18 comments… read them below or add one }

Raghuraman G April 27, 2009 at 5:11 am

Hi Veera, good article.
Meanwhile can u also post a similar one for interface injection.
That would be great !
Good work

Regds

Reply

Veerasundar April 28, 2009 at 4:38 pm

Thank you, Raghu.

Reply

vijay krishna March 31, 2011 at 4:25 pm

Hi,good article

I expect more articles from you.
cover all types of dependency injections in Spring

Reply

Shaik June 16, 2009 at 11:20 pm

Hi these posts are very very usefull.. With this article it is very clear to mw what is DI…
Great… Thanks a lot
Hi can you tell me hwo to set up spring in Eclipse..

-shaik

Reply

Veera June 16, 2009 at 11:24 pm

To setup Spring in any IDE, all you need is put the Spring JAR files in your class path / lib folder (in a web app), create a spring configuration file (applicationContext.xml) in class path and define your beans in it. I don’t think there is any specific configuration to be made in Eclipse for Spring project.

Reply

Shaik November 13, 2009 at 11:03 pm

Hi these posts are very very usefull.. With this article it is very clear to mw what is DI…
Great… Thanks a lot
Hi can you tell me hwo to set up spring in Eclipse..

-shaik

Reply

Veera January 15, 2010 at 8:45 am
Dileep K Mishra January 15, 2010 at 12:40 am

good concept about DI.

Reply

Veera January 15, 2010 at 8:44 am

thanks.

Reply

Sarvesh May 5, 2011 at 4:32 pm

Very Simple and clear.

Reply

Veera May 5, 2011 at 4:55 pm

welcome!

Reply

Kumaresh July 16, 2011 at 6:43 pm

Thanks a lot for this very useful and easy-to-understand article. Understood DI.

Reply

Berthold October 24, 2011 at 1:09 am

Hi, it is very good example. Short and precisly, without unnecessary words.
Tanks, now I understood DI.
Berthold.

Reply

kanchana December 4, 2011 at 6:59 pm

This article is really simple and articulative,now am able to understand DI without much effort,thanks to it.

Reply

Ashok March 16, 2012 at 11:28 am

Really Great !! Its one stop solution for those who hunting for the exact explanation for DI.

Reply

mohan March 26, 2012 at 9:59 am

Its great example and giving very clear about DI. Post more on Spring all injection types.

Reply

yaathirigan April 8, 2012 at 11:21 am

but, apart from reducing few lines of code.. what does this DI brings in for developers ? can you explain with practical situations where DI comes in handy for developers .. especially with the maintenance part of the code

Reply

Veera April 9, 2012 at 3:41 am

The dependency injection helps in lots of ways.. for example, you can easily test your code..during the testing phase you can inject mock objects and during production phase you can inject real objects..

similarly, you can easily switch between different 3rd party services by injecting them at run time..

since it avoids the hard binding, no need to re-code and compile again when you want to switch service..

Reply

Leave a Comment

Previous post:

Next post: