What are Spring Bean Scopes (singleton, prototype, request, session)? स्प्रिंग बीन स्कोप्स (singleton, prototype, request, session) क्या हैं?
Bean scope defines how many instances of a bean the container creates and how long they live. singleton (the default) creates exactly one shared instance per Spring container, reused for every injection point. prototype creates a new instance every time the bean is requested from the container.
Web-aware scopes are also available when using a web application context: request creates one instance per HTTP request, session creates one instance per HTTP session, and application ties an instance to the ServletContext lifecycle. Choosing the wrong scope is a common source of bugs — e.g. injecting a prototype bean into a singleton without a scoped proxy means the prototype is only created once, defeating its purpose.
@Component
@Scope("prototype")
public class ShoppingCart { ... }
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestContext { ... }बीन स्कोप यह डिफाइन करता है कि कंटेनर किसी बीन के कितने इंस्टेंस बनाता है और वे कितने समय तक जीवित रहते हैं। singleton (डिफ़ॉल्ट) हर स्प्रिंग कंटेनर के लिए बिल्कुल एक साझा इंस्टेंस बनाता है। prototype हर बार बीन रिक्वेस्ट होने पर एक नया इंस्टेंस बनाता है।
वेब एप्लिकेशन कॉन्टेक्स्ट का उपयोग करते समय वेब-अवेयर स्कोप्स भी उपलब्ध होते हैं: request हर HTTP रिक्वेस्ट के लिए एक इंस्टेंस बनाता है, session हर HTTP सेशन के लिए। गलत स्कोप चुनना बग्स का एक सामान्य कारण है।
@Component
@Scope("prototype")
public class ShoppingCart { ... }Was this answer clear?