1. Introduction
The @Scope
annotation in Spring Boot (and Spring Framework in general) is used to define the scope of a Spring bean — that is, how and when a new instance of the bean should be created and returned by the Spring container.
By default, all Spring beans are singleton-scoped, meaning only one instance of the bean is created and shared across the entire application context. But using @Scope
, you can change this behavior.
2. Basic Syntax
@Component @Scope("prototype") public class MyBean { // ... }
3. Common Scopes in Spring
Scope Name | Description |
singleton | (Default) A single instance per Spring container |
prototype | A new instance every time the bean is requested |
request | A single instance per HTTP request (only valid in web-aware contexts) |
session | A single instance per HTTP session |
application | A single instance per ServletContext |
websocket | A single instance per WebSocket session |
4. Examples of Each Scope
a) Singleton Scope (Default)
@Component @Scope("singleton") public class SingletonBean { }
Only one instance exists in the Spring context.
b) Prototype Scope
@Component @Scope("prototype") public class PrototypeBean { }
A new instance is created every time this bean is injected or requested from the application context.
c) Request Scope (Only in Web Applications)
@Component @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) public class RequestScopedBean { }
- A new instance is created for every HTTP request.
proxyMode
is required to inject this into singleton-scoped beans.
d) Session Scope
@Component @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) public class SessionScopedBean { }
A new instance is created for each HTTP session.
e) Application Scope
@Component @Scope(value = WebApplicationContext.SCOPE_APPLICATION) public class ApplicationScopedBean { }
Shared across the entire servlet context.
5. Using @Scope with @Bean
@Configuration public class AppConfig { @Bean @Scope("prototype") public MyService myService() { return new MyService(); } }
6. Scope Proxying
For non-singleton beans injected into singleton beans (e.g., request
or session
), you must use proxying:
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)