Possible Duplicates:
What is dependency injection?
What exactly is Spring for?
I want to know
What is Spring Framework? Why and when should one use it in Java Enterprise development?
The answer would be “A dependency injection framework”.
All right, what advantages do we have when using dependency injection frameworks?
The idea of describing classes with setter values and/or constructor parameters seems strange to me.
Why do that? Because we can change the properties without recompiling the project? Is that all that we gain?
Then, what objects should we describe in beans.xml? All objects or only a few?
The simplest answers are welcome
We use Dependency Injection (DI) to implement loose coupling. The choice of any particulary DI Container is not that important.
Every time you create an instance of a class by using the
newkeyword, you tightly couple your code to that class, and you will not be able to substitute that particularl implementation with a different one (at least not without recompiling the code).This would look something like this in C# (but would be equivalent in Java):
This means that if you would later like to use a different MessageService, you can’t.
On the other hand, if you inject an interface into the class and adhere to the Liskov Substition Principle, you will be able to vary the consumer and the service independently.
Although this looks more complicated, we have now managed to follow the Single Responsibility Principle by ensuring that each collaborator does only one thing, and that we can vary both independently of each other.
Furthermore, we can now change MyClass’ behavior without changing the class itself, thus adhering to the Open/Closed Principle.