Middle
What is Spring Scope?
sobes.tech AI
Answer from AI
Spring Scope defines the lifecycle and visibility of a bean. It manages how many instances of the bean will be created and how they will be accessible.
Main types of Scope:
singleton: One instance of the bean is created in the application context. This is the default Scope.prototype: A new instance of the bean is created each time it is requested.request: One instance of the bean is created per HTTP request. Only applicable in web applications.session: One instance of the bean is created per HTTP session. Only applicable in web applications.application: One instance of the bean is created throughout the lifecycle of theServletContext. Only applicable in web applications.
Example of declaring a bean with a specified Scope:
@Component
@Scope("prototype") // Specify prototype scope
public class MyPrototypeBean {
// ...
}
Or in XML configuration:
<bean id="myPrototypeBean" class="com.example.MyPrototypeBean" scope="prototype"/>
Choosing the appropriate Scope depends on the required behavior and state of the bean. Singleton is suitable for stateless beans, while prototype is for stateful or when instance isolation is needed. Request, session, and application are used in web contexts to manage the lifecycle of beans according to requests, sessions, or the entire web application.