Bean Scopes

In Spring Framework, a bean scope defines the lifecycle and visibility of a bean in the Spring IoC container—basically how and when the bean is created and how many instances exist.


Common Bean Scopes in Spring

1. Singleton (default)

  • Only one instance of the bean is created per Spring IoC container.
  • All requests for the bean return the same instance.
@Component
@Scope("singleton") // optional, since it's the default
public class SingletonService {
    public SingletonService() {
        System.out.println("Singleton instance created");
    }
}

Usage:

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

SingletonService s1 = context.getBean(SingletonService.class);
SingletonService s2 = context.getBean(SingletonService.class);

System.out.println(s1 == s2); // true (same instance)

2. Prototype

  • A new instance is created every time the bean is requested.
@Component
@Scope("prototype")
public class PrototypeService {
    public PrototypeService() {
        System.out.println("Prototype instance created");
    }
}

Usage:

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

PrototypeService p1 = context.getBean(PrototypeService.class);
PrototypeService p2 = context.getBean(PrototypeService.class);

System.out.println(p1 == p2); // false (different instances)

3. Request (only in web-aware Spring context)

  • A new bean instance is created per HTTP request.
@Component
@Scope("request")
public class RequestScopedBean {
    public RequestScopedBean() {
        System.out.println("New request bean created");
    }
}

Every HTTP request gets a new instance.


4. Session

  • A new bean instance is created per HTTP session.
@Component
@Scope("session")
public class SessionScopedBean {
    public SessionScopedBean() {
        System.out.println("Session bean created");
    }
}

Every user session has its own instance.


5. Application

  • One instance per ServletContext (shared across all requests and sessions).
@Component
@Scope("application")
public class ApplicationScopedBean {
    public ApplicationScopedBean() {
        System.out.println("Application scope bean created");
    }
}

6. WebSocket

  • One instance per WebSocket session.
@Component
@Scope("websocket")
public class WebSocketScopedBean {
    public WebSocketScopedBean() {
        System.out.println("WebSocket bean created");
    }
}

Quick Summary

ScopeDescriptionExample Use Case
SingletonOne instance per container (default)Service beans, configuration
PrototypeNew instance per requestStateful objects, temporary tasks
RequestNew instance per HTTP requestRequest-specific data (e.g., form objects)
SessionNew instance per HTTP sessionUser session data
ApplicationOne instance per application (ServletContext)Global counters, caches
WebSocketOne instance per WebSocket sessionWebSocket communication state

Leave a Reply