This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Spring and the fly likes What  is dependency injection? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "What  is dependency injection?" Watch "What  is dependency injection?" New topic
Author

What is dependency injection?

Harsha Smith
Ranch Hand

Joined: Jul 18, 2011
Posts: 287
can some explain in a simple terms, the meaning of dependency injection and inversion of control?
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17249
    
    6

Taken from Spring in Action.

You are a SuperHero with Super Powers. How did you get the Super Powers. Did you create them yourself? via "new SuperPower("flying")

or did something outside of you give them to you? you.addSuperPower(superPower);

When something outside of you gives you a superpower it is injecting that super power into you. That is Dependency Injection.

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Harsha Smith
Ranch Hand

Joined: Jul 18, 2011
Posts: 287
Thank you! but isn't there any better example? lines of java code that demonstrate dependency injection?
Ashwin Sridhar
Ranch Hand

Joined: Jul 09, 2011
Posts: 272

Normal instantiation

TestClass obj = new TestClass();

Bean injection

<bean id="obj" class="TestClass"/>


Ashwin Sridhar
SCJP | SCWCD | OCA
Harsha Smith
Ranch Hand

Joined: Jul 18, 2011
Posts: 287
interesting. so beanId here is the reference variable name? advantage of dependency injection over normal instantiation?
Abhay Agarwal
Ranch Hand

Joined: Feb 29, 2008
Posts: 1075
    
    1

you can refer to this URL to get understanding of Dependency Injection

http://martinfowler.com/articles/injection.html


Oracle Java Web Service Developer (1z0-897), Oracle certified Java 7 Programmer, SCJA 1.0, SCJP 5.0, SCWCD 5.0, Oracle SQL Fundamentals I
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17249
    
    6

Ashwin Sridhar wrote:Normal instantiation

TestClass obj = new TestClass();

Bean injection

<bean id="obj" class="TestClass"/>


Actually this is just showing instantiation, not dependency injection.

A a = new A();
B b = new B();
a.setB(b);

That last line I am passing b into a, that is dependency injection through a setter method.

rather than A creating B on its own like

public class A {

B b = new B();
}

Here A is creating its dependency B on its own within itself. This is not dependency injection, but coupling B with A.

Mark
Harsha Smith
Ranch Hand

Joined: Jul 18, 2011
Posts: 287
I am confused. Please tell me what exactly is Dependency Injection. I am a spring dummy. Please don't mind for asking again and again.
Ashwin Sridhar
Ranch Hand

Joined: Jul 09, 2011
Posts: 272

There are two types of injections

setter injection & Constructor injetion.'

previous post is an example of setter injection.

below is for constructor :

<bean id="class1" class="com.class1"/>
<bean id="class2" class="com.class2">
<constructor-arg ref="class1"/>
</bean>

this is similar to

class1 obj1 = new class1();
class2 obj2 = new class2(obj1);

and my first post was mere bean wiring and nothing to do with injections
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17249
    
    6

Harsha Smith wrote:I am confused. Please tell me what exactly is Dependency Injection. I am a spring dummy. Please don't mind for asking again and again.


I am giving you an answer. I am outside of you and passing into you what you need. That is dependency injection.

You do not create and give yourself the answer to yourself, that is not DI.

Mark
Gail Anderson
Author
Ranch Hand

Joined: Jul 07, 2009
Posts: 44
Here is perhaps another way to look at it.

Dependency injection is the mechanism that lets you configure code dependencies, as opposed to have dependencies "hard wired." In Spring, when you configure dependencies, you do so using XML or annotations. There are advantages and disadvantages to each way.

But, there is a bit more to the story. Spring supports building software systems that are loosely coupled. It does this by having you "code to interfaces." When you code to interfaces, you specify the things a service (or repository) object should do. Let's start with a service object. The interface object you design should provide the service-level use cases of your system or subsystem. For example, let's say you have a web application that lists all of the recordings stored somewhere (either in a database or accessible through a web service--it doesn't matter).

Here is a really simple example so you can see some Java code. First, we have an interface that defines our getRecordingList() method.



Then we implement this interface with a Java implementation class. Note below that there is a property called musicDao. This property is an object that does the work. But we don't know how the work is done. In our application code, we just call the interface method getRecordingList().



Now we also have configuration code that says provides the "bean wiring." That is, it performs the dependency injection for us. This is where Spring comes in. The Spring container reads the XML file and (using Java reflection) builds the objects for us. Here is a sample XML code. (Note, that I am only showing part of the system.) Below, you see a bean identified as "musicManager" is instantiated with class music.service.MyMusicManager, which has a property that should be injected with a bean called "musicDao". Here we implement the "musicDao" bean using Jpa, but we could just as easily use another technology: jdbc or web services. The point is that the MusicManager interface simply provides the methods and the implementation is configured. This helps the software engineer create loosely coupled systems.



Does that help?
Craig Walls
author
Ranch Hand

Joined: Sep 19, 2003
Posts: 301
There are a lot of good answers here, but let me try, too...

Virtually every object in an application works with other objects to get their job done. You might have a few "loner" objects, but in a well-designed app, most objects will collaborate with other objects. Therefore, those objects must have references to the objects that they collaborate with, otherwise they won't be able to work together.

The question is: How does an object get a reference to the object(s) it needs? Does it create instances of those objects itself? Does it lookup those objects from some factory? Or is it given those objects by some external source?

If an object creates its own dependencies, that means it is in control of those objects' lifecycles. This isn't necessarily bad...sometimes it may be the right thing to do. But generally, it's bad for an object to be that intimate with the objects it depends on. Not only does it control that object's lifecycle, but it also knows the class that implements that dependency, and is also responsible for any cleanup when it is done with that object. This is a tight-coupling situation and it means that the depending object and the dependency object can't be separated...they're handcuffed together.

If an object looks up its dependencies from some factory or other source, some of the problems with the previous scenario are alleviated. The depending object no longer controls its dependency's lifecycle and it no longer necessarily know how it is implemented. But it may mean that the depending object has another dependency: the factory (or other source) object--where many or all of the same coupling issues are a concern.

However, if an object is *given* its dependencies, the object has no idea of how the dependency was created and when used with interfaces it has no idea what the actual implementation class is. It just gets *something* that it can use, but has no idea where it came from or how it's implemented. This is a low-coupling scenario where the depending object is only truly dependent on the interface that the dependency implements.

That last case is dependency injection in theory. In practice, the dependency can be given to the object via setter methods, constructor arguments, or via other mechanisms. Historically, Spring injected dependencies via constructor arguments and/or setter methods. But newer Spring features make it possible to inject into non-setter methods or even private properties (without a method of any kind).

Spring in Action - Unleash POJO power in your applications!
Modular Java - Discover the secret weapon to modularity on the Java platform!
XDoclet in Action - Your complete guide to code generation with XDoclet.
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17249
    
    6

Craig Walls wrote:There are a lot of good answers here, ...


Of course, because one of them I stole from you. ;)

Mark
Harsha Smith
Ranch Hand

Joined: Jul 18, 2011
Posts: 287
so, Loose coupling is the result of dependency injection....right? now what is IOC and Aspect oriented programming?
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

[Caution: This is best of my knowledge, please correct if I'm wrong]
Harsha Smith wrote:so, Loose coupling is the result of dependency injection....right?

As far as my knowledge goes, yes, Spring advices to use "programming to interface, and not to implementation". All the dependents implementation is injected for you by Spring container.

Harsha Smith wrote:now what is IOC and Aspect oriented programming?

For me, Dependency Injection = IoC + Dependency Inversion.
Where IoC is based on Hollywood principal "Don't call us, we call you", that mean your application doesn't directly called the components, but called and controlled by some other container, like javascript event, onclick, etc. In case of Spring, you don't directly instantiate the objects but Spring control the object instantiation and injection.

Dependency Inversion is: Your high level components (abstraction) should not directly depend upon your low level components (implementation), like

Spring container does this 2 things for you, Using external xml file you inverted the dependencies, thus DI and the container sets the dependencies (not us) thus IOC.

AOP: for me AOP means weaving some code/behavior runtime.


[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17249
    
    6

OK, Loose Coupling can occur in many ways. Coupling itself is not a yes or no thing, it is a a range.

So some keyword in Java makes one class more coupled to another coupled.

Using the keyword "new" tightly couples whatever is to the right of "new"



I just tightly coupled BImpl() to AImpl(), so now if I wanted to change BImpl to AnotherBImpl, I have to go change code and recompile. With coding to an interface like



So with this code, which B implementation is it using? Does AImpl even know what B implementation it is using? Does it have to know? No. Because it can be any B implementation.

So here we don't have coupling between AImpl and any B implementation. AImpl does know about the B interface though so you could say it is coupled with the knowledge of the B interface, but never to exact implementations.

That is why dependency injection is just someone outside of AImpl passing in a B implementation to it.

But coding to an interface helps make DI and loose coupling easier to achieve.

Mark
Rohit Mehta
Ranch Hand

Joined: Mar 11, 2005
Posts: 79

Nice explanation, Craig!
Yosi Pramajaya
Ranch Hand

Joined: Jun 30, 2011
Posts: 46

DI : Injecting some data to your bean ( You have to know what is bean ) through XML/any data source. So that bean become dependent to the XML ( the injector ). That's why it just not called as Data Injection but Dependency Injection.

Hope I could help. I'm a Spring dummy too. But I read so many comments in your post.


Independent Programmer - Technology Enthusiast - JUG Leader from JUG Joglosemar
 
 
subject: What is dependency injection?
 
Similar Threads
difference between Dependency Injection (DI) & Inversion of Control (IOC)
Defination of Spring wiring
Pluggable Components
passing beans..
Inversion of control