Middle
What is the scope of a bean in the context of Spring?
sobes.tech AI
Answer from AI
The scope of a bean in Spring defines its lifecycle, how the instance is created, and how often it is used in the application.
- singleton: One instance of the bean is created for the entire Spring application context. This is the default scope. All requests for the bean with this scope will return the same instance.
- prototype: A new instance of the bean is created each time it is requested from the Spring context.
- request: A new instance of the bean is created for each HTTP request. Relevant for web applications.
- session: A new instance of the bean is created for each HTTP session. Relevant for web applications.
- application: A new instance of the bean is created for the entire
ServletContext. Relevant for web applications.
Example of declaring a bean with prototype scope:
@Component
@Scope("prototype")
public class MyPrototypeBean {
// ...
}
Example of declaring a bean with request scope (for web applications):
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyRequestScopedBean {
// ...
}