Dependency Injection

Let us understand about Dependency Injection


In Spring, Dependency injection(DI) is the design pattern which makes the application components to be loosely coupled by removing the dependency in the program code.

Create Door.java which has dependency on SoundAlaram class as below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.intro;
 
public class Door 
{
    private SoundAlarm alarm;
    
    public void setAlarm(SoundAlarm alarm) {
        this.alarm = alarm;
    }
      public SoundAlarm getAlarm() {
    return alarm;
     }
    
    public void open()
    {
        alarm.activate();
    }
    public void close()
    {
        alarm.deactivate();
    }
}
package com.intro;

public class Door 
{
	private SoundAlarm alarm;
	
	public void setAlarm(SoundAlarm alarm) {
		this.alarm = alarm;
	}
      public SoundAlarm getAlarm() {
  	return alarm;
     }
	
	public void open()
	{
		alarm.activate();
	}
	public void close()
	{
		alarm.deactivate();
	}
}


Create SoundAlarm.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.intro;
 
public class SoundAlarm
{
    
    public SoundAlarm() {
System.out.println("SoundAlarm()");
    }
    
    public void activate() 
    {
        System.out.println("SoundAlarm activated");
    }
    
    public void deactivate() 
    {
        System.out.println("SoundAlarm deactivated");
    }
}
package com.intro;

public class SoundAlarm
{
	
	public SoundAlarm() {
System.out.println("SoundAlarm()");
	}
	
	public void activate() 
	{
		System.out.println("SoundAlarm activated");
	}
	
	public void deactivate() 
	{
		System.out.println("SoundAlarm deactivated");
	}
}


Now whenever at client side we use Door’s Object, first we create SoundAlarm’s object , that is creating ourselves our dependent object.

Observe the below code for the same

1
2
3
4
5
Door doorObj = new Door();
 
SoundAlarm soundAlarm  = new SoundAlarm();//Creating dependent object by ourselves.
 
doorObj.setAlarm(soundAlarm);
Door doorObj = new Door();

SoundAlarm soundAlarm  = new SoundAlarm();//Creating dependent object by ourselves.

doorObj.setAlarm(soundAlarm);

but this is not required if we use spring’s Dependency Injection.

How can we avoid creating dependent object but its injected to Door object ?


solution is Spring Container.

Yes Spring container is responsible to create such dependent objects.

This can be defined using XML file as shown below

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-3.0.xsd">
        <bean id="doorBeanWithSoundAlarm" class="com.intro.Door">
            <property name="alarm" ref="soundAlarmBean"></property>
                  </bean>
        
        <bean id="soundAlarmBean" class="com.intro.SoundAlarm">
                </bean>
        
</beans>
<?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-3.0.xsd">
		<bean id="doorBeanWithSoundAlarm" class="com.intro.Door">
			<property name="alarm" ref="soundAlarmBean"></property>
                  </bean>
		
		<bean id="soundAlarmBean" class="com.intro.SoundAlarm">
                </bean>
		
</beans>


In the above XML file, we are informing the container that, Door class is dependent on SoundAlarm class and henceforth we will get SoundAlarm’s object automatically injected to Door when we get Door’s instance.

Now if i want to call activate() method of SoundAlarm’s class,

We can achieve it in 2 ways

1. Without using Dependency Injection

2. With using Dependency Injection


without using Spring’s Dependency Injection

1
2
3
4
5
6
7
Door doorObj = new Door();
 
SoundAlarm soundAlarm  = new SoundAlarm();//Creating dependent object by ourselves.
 
doorObj.setAlarm(soundAlarm);
 
doorObj.getAlarm().Activate();
Door doorObj = new Door();

SoundAlarm soundAlarm  = new SoundAlarm();//Creating dependent object by ourselves.

doorObj.setAlarm(soundAlarm);

doorObj.getAlarm().Activate();


with using Spring’s Dependency Injection

1
2
3
4
5
ApplicationContext context = new FileSystemXmlApplicationContext("classpath:beans.xml");//loading spring's context
 
Door door =  context.getBean("doorBeanWithSoundAlarm",Door.class);
 
door.getAlarm().Activate();//Not creating dependent object,just creating required object but all dependents are automatically injected
ApplicationContext context = new FileSystemXmlApplicationContext("classpath:beans.xml");//loading spring's context

Door door =  context.getBean("doorBeanWithSoundAlarm",Door.class);

door.getAlarm().Activate();//Not creating dependent object,just creating required object but all dependents are automatically injected


So in Spring’s Dependency Injection, we are not calling door.setAlarm(soundAlarm) to set the dependent object, but Spring has injected it for us.

 
Note:
If Door has several dependent objects like SoundAlarm ,VisualAlarm etc, in this case using Dependency Injection will made our life easy. For that all the dependent objects should be configured well in spring config xml file and automatically dependent objects are getting injected by the spring container.

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on