bean scope container ఎన్ని instances ను సృష్టిస్తుందో మరియు అవి ఎంతకాలం జీవిస్తాయో నియంత్రిస్తుంది. lifecycle callbacks ఒక bean నిర్మించబడిన వెంటనే మరియు అది నాశనం చేయబడటానికి ముందు code ను run చేయడానికి మిమ్మల్ని అనుమతిస్తాయి.
bean scope container ఎన్ని instances ను సృష్టిస్తుందో మరియు అవి ఎంతకాలం జీవిస్తాయో నియంత్రిస్తుంది. lifecycle callbacks ఒక bean నిర్మించబడిన వెంటనే మరియు అది నాశనం చేయబడటానికి ముందు code ను run చేయడానికి మిమ్మల్ని అనుమతిస్తాయి.
@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 { }
క్లాసిక్ trap: ఒక 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 ను పిలవదు — అది వాటిని అప్పగించి tracking ఆపేస్తుంది, కాబట్టి వాటి cleanup మీ బాధ్యత.
ఇది Spring ను magic గా భావించే వారిని container ను అర్థం చేసుకునే వారి నుండి వేరు చేస్తుంది. singleton-ఒక-prototype-ను-ఉంచడం bug ఒక ఇష్టమైన interview దృశ్యం ఎందుకంటే ఇది సూక్ష్మమైనది మరియు నిజమైన production bugs కు కారణమవుతుంది. singletons stateless మరియు thread-safe గా ఉండాలని తెలుసుకోవడం (అవి అన్ని request threads అంతటా పంచుకోబడతాయి) అనేది interviewers వినే ఆచరణాత్మక పాఠం.
జూనియర్ నుండి సీనియర్ వరకు వివరణాత్మక సమాధానాలతో IT ఇంటర్వ్యూ ప్రశ్నల లైబ్రరీ.
విరాళం