Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is Autowiring by Type vs by Name, and what happens when Spring can't resolve a dependency? टाइप बनाम नाम से ऑटोवायरिंग क्या है, और जब स्प्रिंग डिपेंडेंसी रिज़ॉल्व नहीं कर पाता तो क्या होता है?

Answer

By default, @Autowired resolves dependencies by type — Spring looks for a bean matching the field or parameter's declared type. If exactly one candidate exists, it's injected directly; if none exist, Spring throws NoSuchBeanDefinitionException at startup (unless the dependency is marked required = false or wrapped in Optional).

If multiple beans of the same type exist, Spring falls back to matching by field/parameter name against bean names before giving up with a NoUniqueBeanDefinitionException — this is effectively "autowiring by name" as a tiebreaker, though it's less explicit and reliable than using @Qualifier or @Primary to disambiguate directly. Failing fast at startup rather than at runtime is one of Spring's key reliability guarantees for dependency wiring.

@Autowired(required = false)
private AnalyticsService analyticsService; // optional dependency, no exception if missing

डिफ़ॉल्ट रूप से, @Autowired टाइप से डिपेंडेंसीज़ रिज़ॉल्व करता है — स्प्रिंग फील्ड या पैरामीटर के घोषित टाइप से मेल खाने वाला बीन ढूँढता है। यदि बिल्कुल एक उम्मीदवार हो, तो इसे सीधे इंजेक्ट किया जाता है; यदि कोई न हो, तो स्प्रिंग स्टार्टअप पर NoSuchBeanDefinitionException फेंकता है।

यदि एक ही टाइप के कई बीन्स मौजूद हों, तो स्प्रिंग NoUniqueBeanDefinitionException देने से पहले फील्ड/पैरामीटर नाम से बीन नामों के मिलान पर वापस जाता है। रनटाइम के बजाय स्टार्टअप पर फेल होना स्प्रिंग की डिपेंडेंसी वायरिंग की प्रमुख विश्वसनीयता गारंटियों में से एक है।

@Autowired(required = false)
private AnalyticsService analyticsService; // वैकल्पिक डिपेंडेंसी, न होने पर एक्सेप्शन नहीं

Was this answer clear?