Dependency Injection With Spring by Example

I think every developer these days have heard this term “Dependency Injection” or “Inversion of Control” before Martin Fowler coined the term “Dependency Injection”. And how many people are confused by that? Or may be I’m the only one who does not know what it means by injecting something into something and every developer should be happy about it.

I really recommend you to read this article first by Martin Folwer, he has explained it in a very simple way and easy to understand. Additionally, I cannot think of any simpler example to explain than of Martin’s article. So, please do read Martin’s article and Spring in Action for more information.

So, in my example and this is purely from my understanding.

A class student that needs to go to school. You can see that student class is tightly coupled with the class FindARouteToSchool. You can’t have Student without FindARouteToSchool. This is not so bad, but many developers find it not flexible enough. We need to promote loosely coupled.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Student
{
	FindARouteToSchool findARoute;

	public void goToSchool()
	{
		findARoute = new GoByBus();
		findARoute.go();
	}

	public static void main ( String args[] )
	{
		new Student().goToSchool();
	}

}

So, we need something that can inject something into the Student class, so the class is not dependent to FindARouteToSchool. I have chosen Spring to solve the problem and create a setter object to set a reference of the class FindARouteToSchool.

This is the new Student class which has one more method to set FindARouteToSchool reference.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Student
{
	FindARouteToSchool findARoute;

	public void setFindARoute(FindARouteToSchool findARoute)
	{
		this.findARoute = findARoute;
	}

	public void goToSchool()
	{
		findARoute.go();
	}

	public static void main ( String args[] )
	{
		ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-idol.xml");
		Student student = (Student) ctx.getBean("student");
		student.goToSchool();
	}
}

This is the XML configure file of Spring

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

  <bean id="goByTube"
    class="com.noppanit.GoByTube"/>

  <bean id="student" class="com.noppanit.Student" >
    <property name="findARoute" ref="goByTube"></property>
  </bean>
</beans>
Jan 19th, 2011

Comments