![]() |
VOOZH | about |
Dependency Injection (DI) is a design pattern in which an object receives the required objects (dependencies) from an external source instead of creating them itself.
Example: A Car class may require an Engine object to work. Instead of creating the Engine inside the Car class using new Engine(), the Engine object is provided externally by a framework such as Spring.
A dependency is an object that another object requires to perform its work.
The diagram explains:
Without Dependency Injection
Problems with This Approach
Suppose a new engine model is introduced.
Now the Car class must be modified manually.
magine hundreds of classes using the old engine implementation. Updating all these classes manually becomes difficult and time-consuming. This is the problem that Dependency Injection solves.
Dependency Injection provides the required dependency object from an external source instead of creating it manually inside the class.
Instead of:
Engine engine = new DieselEngine();
The dependency is injected externally.
Inversion of Control is a principle in which the responsibility of creating and managing objects is transferred from the application code to a framework or container.
In Spring:
This reduces manual object creation and improves loose coupling.
A vehicle such as a Car depends on multiple components like:
These components are called dependencies. Instead of creating these dependencies manually inside the class, Dependency Injection provides them externally using frameworks such as Spring.
These components can be considered as your dependencies. Without any of these dependencies, our car can never be considered as a complete entity.
In the below solution we will understand above problem using code:
Real-world problem that occurs with Java Dependency Injection Design Pattern
Define a common interface for all engine types.
Create a concrete implementation of the Engine interface.
Legacy Engine
New Engine
Output
New Engine Started
Car is Running
Now the Car class does not depend on a specific engine implementation. The same dependency can be reused across:
without modifying their source code.
Spring Framework provides automatic dependency management using the IoC Container.
The framework:
Use Spring Framework to manage dependencies.
Use @Autowired to inject dependency automatically.
The same dependency can be injected into other vehicle classes.
Bike class:
Scooter class:
@Autowired and @Beanpom.xml:
When the application starts, the Spring IoC Container:
Main Class
New Engine Started
Car is Running