• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

What is dependency injection?

 
Ranch Hand
Posts: 287
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
can some explain in a simple terms, the meaning of dependency injection and inversion of control?
 
ranger
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Harsha Smith
Ranch Hand
Posts: 287
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you! but isn't there any better example? lines of java code that demonstrate dependency injection?
 
Ranch Hand
Posts: 277
Oracle Spring Flex
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Normal instantiation

TestClass obj = new TestClass();

Bean injection

<bean id="obj" class="TestClass"/>
 
Harsha Smith
Ranch Hand
Posts: 287
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
interesting. so beanId here is the reference variable name? advantage of dependency injection over normal instantiation?
 
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you can refer to this URL to get understanding of Dependency Injection

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

 
Mark Spritzler
ranger
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 287
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 277
Oracle Spring Flex
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
 
Author
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
author
Posts: 422
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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).
 
Mark Spritzler
ranger
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 287
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
so, Loose coupling is the result of dependency injection....right? now what is IOC and Aspect oriented programming?
 
Ranch Hand
Posts: 2908
1
Spring Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[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.
 
Mark Spritzler
ranger
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 79
Eclipse IDE Spring Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Nice explanation, Craig!
 
Ranch Hand
Posts: 48
Netbeans IDE Redhat Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
CLUCK LIKE A CHICKEN! Now look at this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic