DIP vs Dependency Injection — principle vs pattern
Fast recall
Quick revision
Core answer
Interview-ready guide
Interview answer
DIP and dependency injection answer different questions. DIP says high-level policy should not depend directly on volatile low-level details; both sides meet through a suitable abstraction. DI means an object receives a collaborator from outside rather than choosing it internally.
For example, OrderService(StripeClient client) is constructor injection, but it still couples the service source to Stripe. OrderService(PaymentGateway gateway) plus a Stripe adapter can follow DIP when the contract belongs to the application policy. Plain bootstrap code can wire that manually. Spring's IoC container automates the same construction and lifecycle work, but annotations and injection alone do not prove DIP.
DIP vs Dependency Injection — principle vs pattern
Direct Answer
DIP is a design principle about the direction and ownership of source dependencies. Dependency injection is a construction technique: an object receives a collaborator from outside. DI can help implement DIP, but it can inject a concrete class and therefore does not guarantee DIP. An IoC container such as Spring automates object creation and injection; manual constructor wiring is also DI.
Code Example
// Application policy declares the capability it needs.
interface PaymentGateway {
void charge(Money amount);
}
final class OrderService {
private final PaymentGateway gateway;
// DI: the collaborator is supplied from outside.
OrderService(PaymentGateway gateway) {
this.gateway = gateway;
}
void checkout(Money total) {
gateway.charge(total);
}
}
final class StripeGateway implements PaymentGateway {
public void charge(Money amount) { /* call Stripe SDK */ }
}
// Manual assembly; Spring could automate this construction.
OrderService service = new OrderService(new StripeGateway());
DI describes how gateway reaches OrderService. DIP describes why the service depends on the application PaymentGateway contract instead of the Stripe detail.
Common Mistakes & Pitfalls
- Calling DIP and DI synonyms: principle and construction technique differ.
- Saying DI is always how DIP is implemented: factories, service locators, and other wiring can still meet an abstraction, though they have trade-offs.
- Assuming an IoC container implies DIP: containers can inject concrete dependencies.
- Calling IoC only a DI tool: IoC also appears in callbacks and framework-controlled lifecycles.
- Avoiding all manual construction: a composition root must still select concrete implementations.
Check your understanding
Answer these without looking back at the article.
- What is constructor injection vs setter injection?
- How does Spring Boot wire dependencies automatically?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.