✅ Inversion of Control (IoC)
🔹 Definition:
Inversion of Control means the control over object creation and dependency management is transferred from the application code to a container or framework.
Instead of creating dependencies manually (
new Service()
), you "invert" control and let the framework provide them (via constructor, setter, or method).
📌 Real Example (Spring Boot):
✅ Dependency Injection (DI)
🔹 Definition:
Dependency Injection is a form of IoC where the framework injects dependencies into a class instead of the class creating them itself.
There are three main types of DI:
-
Constructor Injection (most preferred)
-
Setter Injection
-
Field Injection (less testable)
💡 Why This Pattern (Interview Answer Format)?
I used Dependency Injection to decouple classes from their dependencies and make them testable, modular, and easier to maintain.
It fits well in layered architectures where services, repositories, and controllers are wired together without hardcoding their relationships.
It keeps the design flexible, promotes interface-driven development, and supports mocking in tests.
🧠Common Interview Q&A
❓ Q: What is the difference between IoC and DI?
DI is a concrete way to implement IoC. IoC is the broader concept (you give up control), and DI is how that control is handed over — by injecting dependencies.
❓ Q: How does Spring implement DI?
Spring uses reflection and proxies under the hood. It scans beans, reads annotations like
@Component
,@Autowired
, or uses XML, and injects dependencies into constructors, setters, or fields at runtime.
❓ Q: Why is DI important in microservices?
DI helps inject service interfaces like
EmailService
,UserService
, orPaymentClient
across services. It keeps services loosely coupled, easily mockable, and allows swapping implementations (e.g., REST client vs gRPC).
No comments:
Post a Comment