![]() |
VOOZH | about |
Spring Dependency Injection (DI) is a fundamental concept in the Spring Framework that allows objects to receive their dependencies from an external source rather than creating them internally.
In above Diagram:
Dependency Injection is necessary because directly creating dependencies inside classes can lead to several problems:
1. Tight Coupling
2. Reduced Testability
3. Poor Maintainability
4. Lack of Flexibility and Reusability
5. Centralized Object Management
There are two primary types of Spring Dependency Injection:
Setter DI involves injecting dependencies via setter methods. To configure SDI, the @Autowiredannotation is used along with setter methods and the property is set through the <property> tag in the bean configuration file.
Bean Configuration:
This injects the CsvGFG bean into the GFG object using the setter method (setGeek).
Constructor DI involves injecting dependencies through constructors. To configure CDI, the <constructor-arg> tag is used in the bean configuration file.
Bean Configuration:
This injects the CsvGFG bean into the GFG object via the constructor.
| Setter DI | Constructor DI |
|---|---|
| Creates mutable objects. Dependencies can be modified after creation. | Creates immutable objects. Dependencies can't be modified after creation. |
| Dependencies can be injected later. | All dependencies must be provided at creation. |
| Requires addition of @Autowired annotation. | @Autowired annotation is not needed. |
| It results in circular dependencies or partial dependencies. | It too can have circular dependencies, it just fails faster and more explicitly. |
| Requires framework or manual setter calls for dependency injection in tests. | Easier unit testing - can create objects directly with mock dependencies. |
Prerequisites
👁 Process Flow
- Java JDK installed (8 or above)
- Eclipse IDE or IntelliJ IDEA
- Maven (optional, for dependency management)
- Spring Framework libraries (or use Maven/Gradle)
Add Spring context dependency in pom.xml:
Note: The classes ApplicationContext and ClassPathXmlApplicationContext used in MainApp.java belong to the spring-context module. If this dependency is missing, you will get errors like:
"package org.springframework.context does not exist"
Make sure to add the spring-context dependency and reload your Maven project.
Create interface and classes to define engine behavior and vehicle dependency.
1. Create an interface (IEngine.java)
2. Create implementation class (ToyotaEngine.java)
3. Create dependent class (Vehicle.java)
Configure Spring beans in XML to enable Dependency Injection for objects.
Load Spring container and retrieve beans to test Dependency Injection.
Output:
Toyota Engine started
Vehicle is moving
Toyota Engine started
Vehicle is moving