Possible Duplicate:
What is Inversion of Control?
I'm really confused with the concept of dependency injection.
I'm very new to software field and I have a doubt on the following scenario. Let say I need a Json parser class for my java code, So I'm adding the Json jar when executing the java program using the classpath argument. My program is dependent on Json jar, so that it mean I'm doing a dependency injection here?
An another example will be, using import statement does solve the problem of user class is depending on other class ( like Date in java ) so all these are the concept of dependency injection?
Where I'm making the concept.
Thanks in advance.
It's much more to do with how you link your components together. e.g. in the above, I would expect you to inject your parser into the class that needs it. e.g.
Instead of:
public class MyParserUsingClass {
...
public MyParserUsingClass() {
this.parser = new Parser();
}
}
you would do:
public class MyParserUsingClass {
...
public MyParserUsingClass(Parser injectedParser) {
this.parser = injectedParser;
}
}
Why do this ? Your class using the parser doesn't really care where the parser comes from and should really use an interface rather than a concrete instance. By injecting the parser, you can supply different instances depending on circumstances, mock it out for testing etc. Otherwise the class would just create it internally and you'd have no control over it. This is particularly key for configurable components, components that talk across the network, heavyweight components etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With