ਇੱਕ bean scope ਇਹ ਕੰਟਰੋਲ ਕਰਦਾ ਹੈ ਕਿ container ਕਿੰਨੇ instances ਬਣਾਉਂਦਾ ਹੈ ਅਤੇ ਉਹ ਕਿੰਨੀ ਦੇਰ ਜਿਉਂਦੇ ਹਨ। Lifecycle callbacks ਤੁਹਾਨੂੰ ਇੱਕ bean ਦੇ construct ਹੋਣ ਤੋਂ ਤੁਰੰਤ ਬਾਅਦ ਅਤੇ ਇਸਦੇ destroy ਹੋਣ ਤੋਂ ਠੀਕ ਪਹਿਲਾਂ code ਚਲਾਉਣ ਦਿੰਦੇ ਹਨ।
ਇੱਕ bean scope ਇਹ ਕੰਟਰੋਲ ਕਰਦਾ ਹੈ ਕਿ container ਕਿੰਨੇ instances ਬਣਾਉਂਦਾ ਹੈ ਅਤੇ ਉਹ ਕਿੰਨੀ ਦੇਰ ਜਿਉਂਦੇ ਹਨ। Lifecycle callbacks ਤੁਹਾਨੂੰ ਇੱਕ bean ਦੇ construct ਹੋਣ ਤੋਂ ਤੁਰੰਤ ਬਾਅਦ ਅਤੇ ਇਸਦੇ destroy ਹੋਣ ਤੋਂ ਠੀਕ ਪਹਿਲਾਂ 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 ਨੂੰ ਕਾਲ ਨਹੀਂ ਕਰਦਾ — ਇਹ ਉਹਨਾਂ ਨੂੰ ਸੌਂਪ ਦਿੰਦਾ ਹੈ ਅਤੇ ਉਹਨਾਂ ਨੂੰ track ਕਰਨਾ ਬੰਦ ਕਰ ਦਿੰਦਾ ਹੈ, ਇਸ ਲਈ ਉਹਨਾਂ ਦੀ cleanup ਤੁਹਾਡੀ ਜ਼ਿੰਮੇਵਾਰੀ ਹੈ।
ਇਹ ਉਹਨਾਂ ਲੋਕਾਂ ਨੂੰ ਵੱਖ ਕਰਦਾ ਹੈ ਜੋ Spring ਨੂੰ ਜਾਦੂ ਵਾਂਗ ਵਰਤਦੇ ਹਨ ਉਹਨਾਂ ਤੋਂ ਜੋ container ਨੂੰ ਸਮਝਦੇ ਹਨ। Singleton-ਜੋ-prototype-ਰੱਖਦਾ-ਹੈ bug ਇੱਕ ਮਨਪਸੰਦ interview ਦ੍ਰਿਸ਼ ਹੈ ਕਿਉਂਕਿ ਇਹ ਸੂਖਮ ਹੈ ਅਤੇ ਅਸਲ production bugs ਪੈਦਾ ਕਰਦਾ ਹੈ। ਇਹ ਜਾਣਨਾ ਕਿ singletons ਨੂੰ stateless ਅਤੇ thread-safe ਹੋਣਾ ਚਾਹੀਦਾ ਹੈ (ਇਹ ਸਾਰੇ request threads ਵਿੱਚ ਸਾਂਝੇ ਹੁੰਦੇ ਹਨ) ਉਹ ਵਿਹਾਰਕ ਸਿੱਟਾ ਹੈ ਜੋ interviewer ਸੁਣਨਾ ਚਾਹੁੰਦੇ ਹਨ।
ਵਿਸਤ੍ਰਿਤ ਜਵਾਬਾਂ ਨਾਲ IT ਇੰਟਰਵਿਊ ਸਵਾਲਾਂ ਦੀ ਇੱਕ ਲਾਇਬ੍ਰੇਰੀ — ਜੂਨੀਅਰ ਤੋਂ ਸੀਨੀਅਰ ਤੱਕ।
ਦਾਨ ਕਰੋ