What is the difference between Constructor Injection, Setter Injection, and Field Injection? कंस्ट्रक्टर इंजेक्शन, सेटर इंजेक्शन और फील्ड इंजेक्शन में क्या अंतर है?
Constructor Injection supplies dependencies through a class constructor, making them final and guaranteeing the object is never in a partially-constructed, invalid state. Setter Injection supplies dependencies through public setter methods after construction, useful for optional dependencies. Field Injection uses @Autowired directly on a field, which is the most concise but hardest to test and hides dependencies from the constructor signature.
Constructor Injection is the officially recommended approach by the Spring team: it enables immutability (final fields), makes required dependencies explicit and impossible to forget, works well with unit testing without a Spring context, and surfaces circular dependencies at startup instead of silently working around them.
// Recommended: Constructor Injection
@Service
public class OrderService {
private final PaymentGateway paymentGateway;
public OrderService(PaymentGateway paymentGateway) {
this.paymentGateway = paymentGateway;
}
}
// Discouraged: Field Injection
@Service
public class OrderService {
@Autowired
private PaymentGateway paymentGateway;
}कंस्ट्रक्टर इंजेक्शन क्लास कंस्ट्रक्टर के ज़रिए डिपेंडेंसीज़ देता है, जिससे वे final बन जाती हैं और ऑब्जेक्ट कभी अधूरी, अमान्य स्थिति में नहीं रहता। सेटर इंजेक्शन कंस्ट्रक्शन के बाद पब्लिक सेटर मेथड्स से डिपेंडेंसीज़ देता है, जो वैकल्पिक डिपेंडेंसीज़ के लिए उपयोगी है। फील्ड इंजेक्शन फील्ड पर सीधे @Autowired उपयोग करता है, जो सबसे संक्षिप्त है लेकिन टेस्ट करना सबसे कठिन।
स्प्रिंग टीम द्वारा कंस्ट्रक्टर इंजेक्शन को आधिकारिक रूप से अनुशंसित किया जाता है: यह अपरिवर्तनीयता सक्षम करता है, आवश्यक डिपेंडेंसीज़ को स्पष्ट बनाता है, बिना स्प्रिंग कॉन्टेक्स्ट के यूनिट टेस्टिंग में अच्छी तरह काम करता है, और सर्कुलर डिपेंडेंसीज़ को स्टार्टअप पर ही सामने लाता है।
// अनुशंसित: कंस्ट्रक्टर इंजेक्शन
@Service
public class OrderService {
private final PaymentGateway paymentGateway;
public OrderService(PaymentGateway paymentGateway) {
this.paymentGateway = paymentGateway;
}
}Was this answer clear?