Dependency Injection
Think of a laptop. It needs a processor, RAM, and a hard drive to work. Instead of building these parts inside the laptop, you inject them from outside. If you want a faster processor, you just replace it.
Dependency Injection (DI) works the same way: an object receives its dependencies from an external source (Spring) instead of creating them itself.
Dependency Injection (DI) works the same way: an object receives its dependencies from an external source (Spring) instead of creating them itself.
There are three common ways to inject dependencies in Spring:
- Constructor Injection – dependencies provided via constructor.
- Setter Injection – dependencies set via setter methods.
- Field Injection – dependencies injected directly into fields (using @Autowired).
Example: A
Car depends on an Engine.public class Engine {
public void start() {
System.out.println("Engine started");
}
}
public class Car {
private Engine engine;
public Car(Engine engine) { // Constructor injection
this.engine = engine;
}
public void drive() {
engine.start();
System.out.println("Car is moving");
}
}
To let Spring inject the dependency, you define beans in XML:
<bean id="engine" class="Engine" />
<bean id="car" class="Car">
<constructor-arg ref="engine"/>
</bean>
Two Minute Drill
- Dependency Injection (DI) is a design pattern where objects receive their dependencies from an external container.
- Spring supports constructor, setter, and field injection.
- DI promotes loose coupling and easier testing.
- Use @Autowired for annotation‑based injection (we'll cover that later).
Need more clarification?
Drop us an email at career@quipoinfotech.com
