Master Spring Bean Scopes: Choose the Right Lifecycle for High‑Performance Apps

An in‑depth guide to Spring Bean scopes explains the seven standard scopes—including Singleton, Prototype, Request, Session, Application, Global Session, and WebSocket—detailing their lifecycles, configuration methods, core principles, and best‑practice scenarios to help developers choose the optimal scope for high‑performance, reliable applications.

Cognitive Technology Team
Cognitive Technology Team
Cognitive Technology Team
Master Spring Bean Scopes: Choose the Right Lifecycle for High‑Performance Apps

In the Spring framework, Bean scope is a core design decision that determines the lifecycle, sharing, and resource management of Bean instances. This article systematically analyzes the seven standard scopes (including Web and WebSocket scopes), their underlying principles, configuration practices, and typical scenarios to help developers build high‑performance, reliable applications.

1. Spring Bean Scope Classification and Core Principles

Spring provides 7 standard scopes, divided into general scopes and Web‑specific scopes:

Singleton : applicable to all applications; container‑wide single instance, lifecycle tied to container.

Prototype : all applications; a new instance created on each request.

Request : Web applications; one instance per HTTP request.

Session : Web applications; one instance per HTTP session.

Application : Web applications; one instance per ServletContext.

Global Session : Portlet applications; one instance per global session.

WebSocket : Web applications with real‑time communication; one instance per WebSocket session.

Core Principles :

State isolation – scope must match the Bean’s state (stateless vs stateful).

Resource control – avoid memory leaks (e.g., ensure Session beans are destroyed after timeout).

Thread safety – singleton scope must avoid sharing mutable state.

Performance optimization – prefer reusing instances (Singleton) over frequent creation (Prototype).

2. General Scopes Details

1. Singleton

Features

Default scope – no explicit declaration needed.

Global sharing – only one instance in the container.

Lifecycle – initialized at container startup, destroyed at shutdown (calls @PreDestroy).

Configuration

@Service
public class UserService {
    // Default is Singleton
}

Applicable scenarios

Stateless components such as services, DAOs, utility classes.

Global caches, configuration management.

Precautions

Thread safety – use ThreadLocal or design stateless when mutable state exists.

Dependency injection trap – when a singleton depends on a prototype, the prototype may stay as the first injected instance; resolve with Provider<T>.

2. Prototype

Features

Creates a new instance on each request; Spring does not manage full lifecycle (does not call destroy).

Resource consumption – frequent creation may cause performance issues.

Configuration

@Component
@Scope("prototype")
public class ShoppingCart {
    // New instance per request
}

Applicable scenarios

Stateful temporary objects such as form data in an HTTP request.

Scenarios requiring independent instances, e.g., thread‑safe counters.

Precautions

Memory leak risk – manual destruction logic needed.

Dependency injection trap – singleton depending on prototype should use Provider<T> for lazy injection.

3. Web Scopes Details

1. Request

Features

One instance per HTTP request; destroyed after request ends.

Depends on web environment; requires RequestContextListener configuration.

Configuration

@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public UserPreferences userPreferences() {
    return new UserPreferences();
}

Applicable scenarios

Storing temporary data at request level, such as form submission context.

Precautions

Proxy mode – set proxyMode to allow singleton beans to inject request‑scoped beans.

Async request support – pass context via AsyncContext.

2. Session

Features

One instance per HTTP session; released on timeout or explicit destruction.

Stores user‑level data, suitable for login state.

Configuration

@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public UserSession userSession() {
    return new UserSession();
}

Applicable scenarios

User shopping cart, login status, personalized settings.

Precautions

Timeout management – configure appropriate session-timeout.

Cluster environment – consider session replication or distributed storage (e.g., Redis).

3. Application

Features

One instance per ServletContext; between Singleton and Session.

Application‑level sharing, suitable for global statistics.

Configuration

@Bean
@Scope(WebApplicationContext.SCOPE_APPLICATION)
public AppStatistics statistics() {
    return new AppStatistics();
}

Applicable scenarios

Application‑wide counters, global configuration information.

4. Global Session

Features

Exclusive to Portlet environments; one instance per global Portlet session.

Shares data across Portlets.

Configuration

@Bean
@Scope(value = "globalSession", proxyMode = ScopedProxyMode.TARGET_CLASS)
public GlobalSessionData globalSessionData() {
    return new GlobalSessionData();
}

4. WebSocket Scope Details

1. Core Principle

Lifecycle binding – each WebSocket session corresponds to a Bean instance.

Underlying mechanism – the

WebSocket
onOpen

and onClose events dynamically create and destroy instances.

Applicable scenarios – real‑time communication such as chat rooms, online games, stock push.

2. Configuration

Annotation configuration

@Component
@Scope("websocket")
public class ChatHandler {
    public void onMessage(String message) {
        // Handle real‑time message
    }
}

Enable WebSocket support

@Bean
public ServerEndpointExporter serverEndpointExporter() {
    return new ServerEndpointExporter(); // Register WebSocket endpoints
}

Precautions

Thread safety – ensure state operations inside a WebSocket session are thread‑safe.

Resource release – release WebSocket resources (e.g., connection pools) in @PreDestroy.

5. Scope Selection Strategy and Typical Issues

1. How to choose a scope?

Typical scenarios and recommended scopes:

Stateless components → Singleton

Stateful temporary objects → Prototype

User‑level data → Session

Application‑level shared data → Application

WebSocket session data → WebSocket

2. Typical problems and solutions

(1) Singleton‑Prototype injection issue

// Problem: Singleton depends on Prototype, causing the same Prototype instance to be reused
@Service
public class SingletonService {
    @Autowired
    private PrototypeBean prototype;
}

// Solution: Use Provider<T> for lazy injection
@Service
public class SingletonService {
    @Autowired
    private Provider<PrototypeBean> prototypeProvider;

    public void doSomething() {
        PrototypeBean bean = prototypeProvider.get(); // Gets a new instance each time
    }
}

(2) Web‑scope Bean context loss in async threads

// Problem: Async thread cannot access Request/Session beans
@Async
public void asyncTask() {
    // Cannot access request/session Bean
}

// Solution: Pass context via AsyncContext
@Async
public void asyncTask(AsyncContext context) {
    // Restore context from AsyncContext
}

6. Summary and Best Practices

Key Takeaways

Singleton is the default choice for stateless components.

Prototype is for stateful temporary objects but requires careful resource management.

Web scopes (Request/Session) must align with HTTP lifecycle.

WebSocket scope is optimized for real‑time communication and should bind to session lifecycle.

Best Practices

Avoid injecting prototype beans into singletons unless using Provider<T>.

Configure proxy mode for Web‑scope beans to resolve singleton injection issues.

Set appropriate session timeout to prevent memory leaks.

Ensure thread safety for WebSocket‑scoped beans.

By deeply understanding the principles and use cases of Spring Bean scopes, developers can manage object lifecycles more efficiently, optimize performance, and avoid common pitfalls, ultimately building high‑quality Spring applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentSpringWebSocketdependency-injectionBean Scope
Cognitive Technology Team
Written by

Cognitive Technology Team

Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.