What is Dependency Injection?
4 years ago
Advance Java
- Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application.
- Dependency Injection makes our programming code loosely coupled.
- DI is a concept of injecting an object into a class rather than explicitly creating object in a class, since IoC container injects object into class during runtime.
Example:Standard code without Dependency Injection
public class TextEditor {
private SpellChecker spellChecker;
public TextEditor() {
spellChecker = new SpellChecker();
}
}
Example: Code with Dependency Injection
public class TextEditor {
private SpellChecker spellChecker;
public TextEditor(SpellChecker spellChecker) { this.spellChecker = spellChecker;
}
}
Here, the TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented independently and will be provided to the TextEditor at the time of TextEditor instantiation. This entire procedure is controlled by the Spring Framework.
Bijay Satyal
Nov 2, 2021