Learnitweb

@Scope annotation

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 NameDescription
singleton(Default) A single instance per Spring container
prototypeA new instance every time the bean is requested
requestA single instance per HTTP request (only valid in web-aware contexts)
sessionA single instance per HTTP session
applicationA single instance per ServletContext
websocketA 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)