Bean scope નિયંત્રિત કરે છે કે container કેટલા instances બનાવે અને તેઓ કેટલો સમય જીવે. Lifecycle callbacks તમને bean બન્યા પછી તરત અને તે destroy થાય તે પહેલાં code ચલાવવા દે છે.
Bean scope નિયંત્રિત કરે છે કે container કેટલા instances બનાવે અને તેઓ કેટલો સમય જીવે. Lifecycle callbacks તમને bean બન્યા પછી તરત અને તે 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 { }
ક્લાસિક જાળ: 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 કરતું નથી — તે તેમને સોંપી દે છે અને track કરવાનું બંધ કરે છે, તેથી તેમની cleanup ની જવાબદારી તમારી છે.
આ Spring ને જાદુ ગણનારા લોકોને container સમજનારાઓથી અલગ પાડે છે. Singleton-માં-prototype રાખવાનો bug એક પ્રિય interview દૃશ્ય છે કારણ કે તે સૂક્ષ્મ છે અને વાસ્તવિક production bugs કરાવે છે. Singletons stateless અને thread-safe હોવા જોઈએ (તેઓ બધા request threads ના પાર શેર થાય છે) એ જાણવું એ વ્યવહારુ મુદ્દો છે જે interviewers સાંભળે છે.
વિગતવાર જવાબો સાથે IT ઇન્ટરવ્યૂ પ્રશ્નોની લાઇબ્રેરી — જુનિયરથી સિનિયર સુધી.
દાન કરો