what is dependency injection in java
Dependency injection in Java is a way of giving a class the objects it needs from the outside instead of letting the class create them itself. That makes code less coupled , easier to test, and easier to change later.
Quick Scoop
In a typical Java program, a class might directly create its own dependencies
with new, which ties that class to specific implementations. With dependency
injection, those dependencies are passed in, often through a constructor or a
setter, so the class focuses on its own job.
Simple example
Instead of this:
java
class Car {
private Engine engine = new Engine();
}
You do this:
java
class Car {
private final Engine engine;
Car(Engine engine) {
this.engine = engine;
}
}
Now Car does not care which Engine implementation it gets, as long as it
works like an engine. That makes testing easier because you can pass a fake or
mock engine during tests.
Common types
- Constructor injection: the dependency is passed in through the constructor.
- Setter injection: the dependency is set later through a setter method.
- Field injection: the dependency is injected directly into a field, often by a framework like Spring.
Why it matters
Dependency injection supports loose coupling, which means classes depend on abstractions more than concrete classes. It also improves maintainability because you can swap implementations without rewriting the whole class. In practice, frameworks like Spring use DI heavily to manage application objects and their relationships.
In one line
Dependency injection means: βdonβt build what you need inside the class; receive it from outside.β
Would you like a tiny Spring example next?