Bean scope ठरवतो की container किती instances तयार करते आणि ती किती काळ जगतात. Lifecycle callbacks मुळे तुम्ही bean बांधल्यानंतर लगेच आणि तो नष्ट होण्याच्या अगदी आधी code चालवू शकता.
Bean scope ठरवतो की container किती instances तयार करते आणि ती किती काळ जगतात. Lifecycle callbacks मुळे तुम्ही bean बांधल्यानंतर लगेच आणि तो नष्ट होण्याच्या अगदी आधी 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 { }
पारंपरिक सापळा: singleton मध्ये prototype 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 करत नाही — ते त्यांना सुपूर्द करून त्यांचा मागोवा घेणे थांबवते, त्यामुळे त्यांचे cleanup तुमच्या जबाबदारीचे असते.
हे Spring ला जादू मानणाऱ्यांना container समजणाऱ्यांपासून वेगळे करते. singleton मध्ये prototype धरून ठेवणारा bug हा आवडता interview प्रसंग आहे कारण तो सूक्ष्म आहे आणि खऱ्या production bugs निर्माण करतो. singletons stateless आणि thread-safe असले पाहिजेत (ते सर्व request threads मध्ये सामायिक असतात) हे जाणणे हा व्यावहारिक बोध आहे जो interviewers ऐकू इच्छितात.
सविस्तर उत्तरांसह IT मुलाखत प्रश्नांचे ग्रंथालय — Junior पासून Senior पर्यंत.
देणगी द्या