What is Dependency Injection and what problem does it solve? डिपेंडेंसी इंजेक्शन क्या है और यह किस समस्या को हल करता है?
Dependency Injection (DI) is a design pattern where an object's dependencies are supplied by an external source (the Spring IoC container) rather than the object creating them itself with new. Instead of a class instantiating its own collaborators, those collaborators are "injected" through the constructor, a setter, or a field.
DI solves tight coupling: without it, classes are hard-wired to specific implementations, making unit testing difficult (you can't easily substitute a mock) and changes ripple across the codebase. With DI, classes depend on abstractions, implementations can be swapped without touching consumer code, and testing becomes straightforward since dependencies can be mocked and injected directly.
@Service
public class OrderService {
private final PaymentGateway paymentGateway; // injected, not "new"ed
public OrderService(PaymentGateway paymentGateway) {
this.paymentGateway = paymentGateway;
}
}डिपेंडेंसी इंजेक्शन (DI) एक डिज़ाइन पैटर्न है जिसमें किसी ऑब्जेक्ट की डिपेंडेंसीज़ बाहरी स्रोत (स्प्रिंग IoC कंटेनर) से दी जाती हैं, न कि ऑब्जेक्ट खुद new से बनाता है। किसी क्लास द्वारा अपने कोलैबोरेटर्स को खुद इंस्टैंशिएट करने के बजाय, उन्हें कंस्ट्रक्टर, सेटर, या फील्ड के ज़रिए "इंजेक्ट" किया जाता है।
DI टाइट कपलिंग को हल करता है: इसके बिना, क्लासेज़ विशिष्ट इम्प्लीमेंटेशन से जुड़ी होती हैं, जिससे यूनिट टेस्टिंग मुश्किल होती है। DI के साथ, क्लासेज़ एब्सट्रैक्शन पर निर्भर होती हैं, इम्प्लीमेंटेशन बिना कंज़्यूमर कोड छुए बदले जा सकते हैं, और टेस्टिंग आसान हो जाती है।
@Service
public class OrderService {
private final PaymentGateway paymentGateway; // इंजेक्ट किया गया, "new" नहीं
public OrderService(PaymentGateway paymentGateway) {
this.paymentGateway = paymentGateway;
}
}Was this answer clear?