![]() |
VOOZH | about |
Dependency Injection is a design pattern where the Spring IoC container is responsible for providing the required dependencies of a class rather than the class creating them itself.
Instead of manually instantiating objects, Spring automatically injects them at runtime, either through constructors or setter methods.
Without DI, classes are tightly coupled since they instantiate their dependencies directly:
This approach makes testing and maintenance difficult.
With Spring DI, the container injects dependencies externally:
Now, A and B are loosely coupled. The Spring container manages their lifecycle and relationships.
There are two types of dependency injection in spring
In Setter-Based DI, the Spring container:
Dependencies are injected into a bean using setter methods defined in the Spring configuration XML file. The Spring container creates the bean instance and assigns property values using <property> tags.
Student.java:
Output:
Student{studentName=John, studentCourse=Spring Framework}
In modern Spring applications, annotations are preferred over XML. The same example can be implemented as follows:
Output:
Student{studentName=John, studentCourse=Spring Framework}
Java-based configuration replaces XML with annotations and Java classes.
Output:
Student{studentName=John, studentCourse=Spring Framework}