Dependency Injection (DI) with Spring

Last modified on October 14th, 2014 by Joe.

In this tutorial we will learn about what is dependency injection (DI) and how Spring framework supports DI. Couple of weeks back we saw a tutorial on Spring MVC and this is a continuation in this series.

Table of Contents

  1. Dependency Injection
  2. Difference between Dependency Injection and Factory
  3. Advantages of Dependency Injection
  4. Dependency Injection Types
  5. Spring DI
  6. Spring Dependency Injection using Annotations
  7. Spring Dependency Injection using XML
  8. Download Spring IOC Example Source Code

1. Dependency Injection

Dependency injection is a jargon created by Martin Fowler and it is also called as inversion of control. In object oriented design, objects have relationship with one another. A class (A) can have attributes (B) and methods. Those attributes are again instances of another class (C). If class (A) wants to work and perform its objective, attributes (B) should be instantiated.

There are different ways to instantiate an object and we have seen a lot in our design pattern tutorial series. A simple and direct way is to use the “new” operator and call the constructor of Class (C) where we need that instance in class (A). This is class A has obsolute control over creation of attribute (B). It decides which class (C) to call and how to call etc.

Now, if we outsource that ‘instantiation and supplying an instance’ job to some third party. Class (A) needs instance of class (C) to operate, but it outsources that responsibility to some third party. The designated third party, decides the moment of creation and the type to use to create the instance. The dependency between class (A) and class (C) is injected by a third party. Whole of this agreement involves some configuration information too. This whole process is called dependency injection.

2. Difference between Dependency Injection and Factory

Factory design pattern and dependency injection may look related but we look at them with microscope then we can understand the are different. Even if we use a factory the dependent class has the responsibility of creating the instance but the core of dependency injection is separating that responsibility to external component.

2.1 Factory Example:

Class A {
private C obj;

public void someMethod() {
	...
	this.obj = MyObjectFactory.getC();
	...
}
}

2.2 With Dependency Injection:

Class A {
private C obj;

public void someMethod(C obj) {
	...
	this.obj = obj;
	...
}
}

With DI the contract is different, pass C’s instance to get the job done. So the responsibility is with an external person to decide.

3. Advantages of Dependency Injection

  • Loosely couple architecture.
  • Separation of responsibility
  • Configuration and code is separate.
  • Using configuration, a different implementation can be supplied without changing the dependent code.
  • Testing can be performed using mock objects.

4. Dependency Injection Types

Dependency injection is classified into three categories namely,

  1. Constructor Injection
  2. Setter Injection
  3. Interface-based Injection

Definition for the above are explicit. When the dependency is solved using constructor it is called constructor injection :-) That is, the dependent object is passed as a parameter in the dependent class’s constructor. Similarly for setter injection, the instance is injected using a setter method. In interface-based dependency injection, we will have an interface and on implementing it we will get the instance injected.

5. Spring DI

Spring framework provides many modules and its core has an inversion of control (IOC) container. Spring’s IOC container is light-weight and it manages the dependency between objects using configurations. It wires the related objects together, instantiates and supplies them based on configuration. In Spring, these objects are called managed objects. Spring and dependency injection is a large area and requires multiple articles to get an indepth idea. In this tutorial, my intent is to give an introduction and subsequently write more articles on it.

Two most popular ways in Spring for DI is, constructor and setter injection. Configuration for dependency are done using Spring-configuration XML or using annotations. Annotations are mostly preferred for their ease of use. Spring manages these objects using BeanFactory. When an instance is created, by default they are singletons and this can be changed using the configuration.

5.1 Circular Dependency

What is circular dependency and tell about it is a popular question in Spring interviews. A -> B -> A, A is dependent on B and vice-versa. Spring’s IOC container will detect such circular dependencies at runtime and throws ObjectCurrentlyInCreationException. This is more prevalent in the case of constructor injection.

6. Spring Dependency Injection using Annotations

WildAnimal.java – Interface backbone using which dependency injection is done.

package com.javapapers.spring.ioc;

public interface WildAnimal {
	public String sound() ;
}

Lion.java – Implements the above interface and becomes a possible candidate for injection.

package com.javapapers.spring.ioc;

public class Lion implements WildAnimal {
	public String sound() {
		return "Roar";
	}
}

Wolf.java – another implementation of interface. This is the selected implementation for injection. @Service tells the spring IOC container to use this class.

package com.javapapers.spring.ioc;
import org.springframework.stereotype.Service;

@Service
public class Wolf implements WildAnimal {
	public String sound() {
		return "Howl";
	}
}

Zoo.java – Zoo depends on WildAnimal and uses setter injection. @Autowired tells the Spring IOC container to find configured object of this type and inject an instance at runtime.

package com.javapapers.spring.ioc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class Zoo {
	private WildAnimal wild;

	@Autowired
	public void setWild(WildAnimal wild) {
		this.wild = wild;
	}

	public void testSound() {
		System.out.println(wild.sound());
	}

}

spring-context.xml – gives the configuration information to the spring container. In this I describe that we are using annotation based configurations.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- Dependency Injection with annotations -->
	<context:component-scan base-package="com.javapapers.spring.ioc" />
		<mvc:annotation-driven />

	<!-- Dependency Injection without annotations -->
	<!--
	<bean id="wild" class="com.javapapers.spring.ioc.Wolf" />
	<bean id="zoo" class="com.javapapers.spring.ioc.Zoo">
		<property name="wild" ref="wild" />
	</bean>
	 -->

</beans>

TestDI.java – loads the spring configuration and gets the bean. Spring IOC container based on annotations, provides the Wolf.java instance at runtime.

package com.javapapers.spring.ioc;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDI {

	public static void main(String[] args) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext("META-INF/spring-context.xml");
		BeanFactory factory = appContext;
		Zoo zoo = (Zoo) factory.getBean("zoo");
		zoo.testSound();
	}
}

7. Spring Dependency Injection using XML

We can remove all the annotations in the java classes. In spring configuration we declare the chosen implementation to supply at runtime.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- Dependency Injection with annotations -->
	<!-- <context:component-scan base-package="com.javapapers.spring.ioc" />
		<mvc:annotation-driven /> -->

	<!-- Dependency Injection without annotations -->
	<bean id="wild" class="com.javapapers.spring.ioc.Wolf" />
	<bean id="zoo" class="com.javapapers.spring.ioc.Zoo">
		<property name="wild" ref="wild" />
	</bean>

</beans>

8. Download Spring IOC Example Source Code

Download SpringIOC Example Source Code

Comments on "Dependency Injection (DI) with Spring"

  1. laxman says:

    nice collections

  2. Farrukh says:

    Very nice tutorial, respect to author.

  3. vikas says:

    nice tutorial……………

  4. Archana says:

    very nice example to explain DI…

  5. vivek says:

    Thanks Joe,

    Expecting more in up coming Spring concepts

  6. Suresh says:

    Expecting more in spring concepts.Nice Explain.

    Thanks Joe,

  7. Hitesh says:

    good one sir :)

  8. Ganesh says:

    Your wording is so much clear and perfect. Articles are easy to understand.. Hoping to see lot more topics to cover from Spring.

  9. Anil says:

    Yah this material is helping me alot .
    dep-inj topic is very good and i am also expecting more concepts from Spring

  10. Naresh says:

    Nice one sir, with easy presentation. I hope u vl cover or update concepts of STRUTS also. If u provide STRUTS also it will be very helpful. Thanks..

  11. Anonymous says:

    Very nice explanation.. Expecting more from you about spring with database connection with example.. Hope you will conver lot about spring in your next article.

    Hots of your excellent work.

  12. Thiyarajan says:

    Thanks Joe sir,

    Its a very nice tutorial to learn and understand spring.

  13. Vgopalkr says:

    Simple and easy understand. Thanks Joe!

  14. deepak says:

    One Word. BRILLIANT! An explanation given in such a neat and simple way that makes the concept so clear. Great work, Keep it flowing!

  15. deepak says:

    Looking forward for articles on Hibernate as well :)

  16. Anonymous says:

    explanation given in such simple way that makes the concept so clear.

  17. krishna says:

    Good one.

  18. sheik abdulla says:

    Great one, Joe ! Thanks much.

  19. senthil says:

    Good

  20. sridhar says:

    Very Nice Explanation, makes feel to understand so simple ! Thank You

  21. jcaleb says:

    i cant live without Spring nowadays. It’a a must when coding java web projects

  22. Sreenivas says:

    Great article,Many thanks sir..

  23. Devisingh says:

    Great helping source sir..

    Look forward more spring hibernate tutorials

  24. manju says:

    its very useful thank u

  25. Anonymous says:

    Nice tutorial , easy to understand for the beginners and explained with the clarity.

  26. sach says:

    gud

  27. kumar says:

    Nice tutorial….can u provide this explanation with small demonstration……..

  28. Anonymous says:

    I didn’t get much info regarding the difference between Annotation based & XML based DI. Is it the only difference is commenting ”
    ??
    How i can create zoo with lion / wolf at runtime interchangeble?

  29. vasandharaj says:

    Its a nice tutorial..

  30. sanjay says:

    ooosm tutorial for DI intro.

  31. ashish says:

    hii joe ,
    can u plz show hot to do this program using xml configurations instead of annotations…

  32. Karthick says:

    Hi, I don’t want to use anything in my Spring XML. And in my web application, how do I achieve DI. Is there a way to achieve it only by using Annotations? Something similar to @Inject in JavaEE 6 standards..is there a way to achieve it?

  33. Karthick says:

    I mean, I dont want to have this piece of code,

    ApplicationContext appContext = new ClassPathXmlApplicationContext(“META-INF/spring-context.xml”);
    BeanFactory factory = appContext;
    Zoo zoo = (Zoo) factory.getBean(“zoo”);

  34. Anonymous says:

    Great tutorial using simplest language…
    Good job Sir jee…

  35. K.n.raj says:

    thank you sir.
    sir ur explanation is super on dependency injection.

    sir, i want spring acegi security means authentication and autherization concepts with small example.
    please tell me sir…

  36. Eswari says:

    Really very good explanation for DI.. Thank you Joe.

  37. anjani says:

    VERY VERY NICE EXPL

  38. sai says:

    Using

    Zoo zoo = (Zoo) factory.getBean(“zoo”);

    Is not a dependency Injection. I found in some articles found in the internet. Would you agree?

  39. Joe says:

    Yes this is not dependency injection.

  40. nikhil says:

    can you please post constructor based dependency injection too and how to pass a dbobject in constructor

  41. Raj says:

    the same example is exist in many sites…post some other example….

  42. madhavi says:

    Nice tutorial. .thanx. .

  43. Anonymous says:

    very usefull

  44. Mark says:

    very useful sir

  45. Manoj Mishra says:

    Very Good and Helpfull

  46. Mansur says:

    Easy to Understand and the examples are quite self explanatory.

    Thanks a lot!

  47. ChandraSekhar rao Naidu` says:

    Good work………….

  48. chris says:

    THANK YOU!! I have spent the entire afternoon trying to understand DI, but I was still so confused. I finally got it after reading your little tutorial.

  49. Sanjay says:

    Thanks Joe, you explained well… I have downloaded this source code but unbale to run it because of jars.. could you please let me know about required jars to execute it. Many Thanks in Advance.

  50. RAFI says:

    good one thanks…………………

  51. soma_ says:

    Thanks for the Post Joe.. But I cant able to understand where DI working in this example….Could you pls explain

  52. Sameer Soni says:

    Very Nice and concise tutorial. Thanks.

  53. Rahul S says:

    Hi ,

    I am new to spring framework.I think in above example, you should define bean in application context xml file whether it’s autowired or xml based configuration .

    but in source code you have written,


    <!–

    –>

    why you commented all beans if you are configuring using annotation??
    Please reply me i am new to this framework.

  54. p satapathy says:

    Thanks a lot joy.for such a useful and easily understandable material..each time i am reading your block and getting more and more knowledge…

  55. Harsha says:

    Thank you Joe ! Simple and good explanation , that is your way .

  56. Daisy says:

    Very nice explanation.. Expecting more from you about spring

  57. Devendra Singh says:

    Nice one.

  58. av says:

    It’s the best, srsly! :)

  59. DineshKumar says:

    Hi, I got an error while eaxecute the above code.

    Error occurred during initialization of VM
    java.lang.UnsatisfiedLinkError: java.lang.Class.desiredAssertionStatus0(Ljava/lang/Class;)Z
    <> “

  60. Bhagwan singh says:

    Hi
    I have one confusion if I have interface which is implements by class A and I have some method in that class A but by using dependency injection i want to use those method in class B how I can do it Please clear this doubt.
    thanks in advance

  61. Anonymous says:

    easy to understand

  62. Mercy devakirubai says:

    easy to understand

  63. Siva says:

    Gud One!!!! Very helpful!!! Thanks…

  64. avinash says:

    nice tutorial

  65. Anitha says:

    nice collections very useful for us, please provide struts materials also, it will be more useful to us

    Regards
    anitha

  66. Anonymous says:

    awesom

  67. Laukendra says:

    Awesom…….. :)

  68. sai says:

    Thanks for the nice article. Could you please explain the elegant way of coding if Lion is also annotated as service and at run time dynamically need to inject either Lion or wolf?

  69. Anonymous says:

    Tell me how to resolve circular dependancy?

  70. panupong says:

    thank a lot , very easy to understand tutorial

  71. panupong says:

    thank a lot , nice tutorial

  72. krishna says:

    It is very nice article.
    I have few questions to ask on Circular dependency?

    How the spring container detects that there is a circular dependency exists between classes?

    Could you please provide me an example where circular dependency exists?

  73. Aman says:

    Why
    Zoo zoo = (Zoo) factory.getBean(“zoo”); this is not dependency injection.

    Many people saying interface injection is not possible in spring ,can you tell me why and what is exactly interface injection?

  74. Satish Koleti says:

    Very nice explanation.. Thank you.

  75. Naveen Kocherla says:

    Hi joe,
    can you please explain the benefits of dependency injection in detail?

  76. Baskar says:

    Hi Joe,
    It is good informative and understandable. you have explained very well. “DON’T CALL ME, I’LL CALL YOU” This one sentence enough to understand the concept of Dependency Injection. I expecting more on spring from you.

  77. Pankaj Shet says:

    Hi Joe,

    I got this interview question in one of the interviews.

    Is IOC possible with DI?

    I answered Yes.

    DI is Injecting Dependancies.
    Since the process of DI is managed by the container and not us , the flow is reversed hence it is Inversion Of Control.

    So ideally, The Servlet which instantiated by container, whose lifecyle methods are managed by the web container, is also IOC? but not DI?

    Am I correct? Please explain.

    Regards,
    -Pankaj.

  78. Naveen Kocherla says:

    Hi joe, Nice article
    I have a question, can you explain these line clearly?

    ” it manages the dependency between objects using configurations. It wires the related objects together, instantiates and supplies them based on configuration. In Spring, these objects are called managed objects”

    What is this wiring? and wiring together?

  79. ABhishek says:

    Dear Joe,

    Please explain how spring internally make singletone
    Does it make private constructor , then static instance variable
    And check in if else condition.Please help about the internal implementation of
    Singleton and prototype.

    Tahnks
    Abhishek

  80. Abhinav says:

    Thanks a lot for this..

  81. Anirudh says:

    Dear Joe,
    I am new to Spring, and currently I am working on Flex project which uses Spring WebMVC framework. I am unable to understand one thing, I have a jar in my lib folder which uses a config.xml file having a Spring factory defined. Now I am having a doubt as to how I can use this SpringFactory id in my config.xml file so that there will be two factories which will be configured.

    Thanks in advance.

  82. madhuri tina says:

    It’s good thanks for the sharing information

  83. Anoymous says:

    I’ve been looking for a clear explanation of this topic for awhile now and couldn’t find one. Thanks actually explaining Spring clearly.

  84. Harsha says:

    Hi Joe,
    I would like to know if we can run a spring application without activating either of the spring containers(Bean Factory and Application Context). I am working on a spring web application where i didn’t see any activation of the above mentioned containers in java code. Your answer would be much appreciated.

    Thanks,
    Sriharsha K

  85. jyoti says:

    Nice article for beginners to understand the spring concepts.

  86. Cyril says:

    Thanks for your spring materials. And one more request (from everyone) could you please add information about MAVEN. Coz that really help us to work with better understanding.

    Like * Purpose
    * Use
    * Advantages
    * How to work with

    Thanks in advance.

    Cyril

Comments are closed for "Dependency Injection (DI) with Spring".