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


Create SoundAlarm.java

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


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. Door doorObj = new Door();
  2.  
  3. SoundAlarm soundAlarm  = new SoundAlarm();//Creating dependent object by ourselves.
  4.  
  5. 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. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  5.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  6.         <bean id="doorBeanWithSoundAlarm" class="com.intro.Door">
  7.             <property name="alarm" ref="soundAlarmBean"></property>
  8.                   </bean>
  9.        
  10.         <bean id="soundAlarmBean" class="com.intro.SoundAlarm">
  11.                 </bean>
  12.        
  13. </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. Door doorObj = new Door();
  2.  
  3. SoundAlarm soundAlarm  = new SoundAlarm();//Creating dependent object by ourselves.
  4.  
  5. doorObj.setAlarm(soundAlarm);
  6.  
  7. 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. ApplicationContext context = new FileSystemXmlApplicationContext("classpath:beans.xml");//loading spring's context
  2.  
  3. Door door =  context.getBean("doorBeanWithSoundAlarm",Door.class);
  4.  
  5. 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

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