एक bean scope नियंत्रित करता है कि container कितने instances बनाता है और वे कितने समय तक जीते हैं। Lifecycle callbacks आपको किसी bean के construct होने के तुरंत बाद और उसके नष्ट होने के ठीक पहले code चलाने देते हैं।
एक bean scope नियंत्रित करता है कि container कितने instances बनाता है और वे कितने समय तक जीते हैं। Lifecycle callbacks आपको किसी bean के construct होने के तुरंत बाद और उसके नष्ट होने के ठीक पहले code चलाने देते हैं।
@Service // singleton by default — one shared OrderService for the whole app
public class OrderService { }
@Component
@Scope("prototype") // fresh instance on every getBean/inject
public class ReportBuilder { }
क्लासिक जाल: एक prototype को singleton में inject करना। Singleton एक बार wire होता है, इसलिए वह हमेशा के लिए एक ही prototype instance रखता है — "हर बार नया" वाला वादा टूट जाता है। इसे @Lookup, एक ObjectProvider<ReportBuilder>, या scoped-proxy से ठीक करें।
@Component
public class ConnectionPool {
@PostConstruct // runs after dependencies are injected, before use
public void open() { /* open sockets, warm caches */ }
@PreDestroy // runs on graceful container shutdown (singletons only)
public void close() { /* release resources */ }
}
महत्वपूर्ण: Spring prototype beans पर @PreDestroy नहीं call करता — वह उन्हें सौंप देता है और उन्हें track करना बंद कर देता है, इसलिए उनकी cleanup आपकी ज़िम्मेदारी है।
यह उन लोगों को अलग करता है जो Spring को जादू मानते हैं उनसे जो container को समझते हैं। Singleton-में-prototype वाला bug एक पसंदीदा interview परिदृश्य है क्योंकि यह सूक्ष्म है और असली production bugs पैदा करता है। यह जानना कि singletons को stateless और thread-safe होना चाहिए (वे सभी request threads में साझा होते हैं) वह व्यावहारिक सीख है जिसे interviewer सुनना चाहते हैं।
विस्तृत उत्तरों के साथ IT इंटरव्यू प्रश्नों की एक लाइब्रेरी — जूनियर से सीनियर तक।
दान करें