Spring Bean Scopes Explained with Examples

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.

🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.

▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube

When working with Spring Framework, understanding bean scopes is crucial for managing the lifecycle and visibility of your beans. Spring allows you to define how and when the beans should be created, shared, or disposed.

In this article, we’ll explore all the major bean scopes in Spring — complete with simple explanations, real-world use cases, and working examples.

🚀 What Is a Bean Scope?

A bean scope defines the lifecycle of a bean instance — how long it lives, how many instances are created, and whether it's shared across requests or created new each time.

By default, every Spring bean is a singleton, but Spring provides several other scopes.

🧾 Commonly Used Scopes in Spring

Scope Description Context
singleton One shared instance per Spring container Default
prototype New instance every time the bean is requested All
request One instance per HTTP request Web
session One instance per HTTP session Web
application One instance per ServletContext Web
websocket One instance per WebSocket session WebSocket

1. 🧠 Singleton Scope (Default)

Only one instance of the bean is created per Spring container. All requests refer to the same bean.

📌 Example

@Component
public class AppLogger {
    public AppLogger() {
        System.out.println("AppLogger initialized");
    }
}

✅ Use Case:

  • Service layer components like UserService, ProductService

2. 🌀 Prototype Scope

A new bean instance is created every time the bean is requested from the container.

📌 Example

@Component
@Scope("prototype")
public class Notification {
    public Notification() {
        System.out.println("New Notification created");
    }
}
@Autowired
private ApplicationContext context;

public void send() {
    Notification n1 = context.getBean(Notification.class);
    Notification n2 = context.getBean(Notification.class);
    // n1 != n2
}

✅ Use Case:

  • When the bean maintains state and needs to be fresh for each use
  • Use carefully with scoped proxies when injecting into singleton beans

3. 🌐 Request Scope

A new instance is created per HTTP request. Common in web applications.

📌 Example

@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestInfo {
    private final UUID id = UUID.randomUUID();
    public UUID getId() { return id; }
}
@RestController
public class TestController {
    @Autowired
    private RequestInfo requestInfo;

    @GetMapping("/id")
    public String getRequestId() {
        return "Request ID: " + requestInfo.getId();
    }
}

✅ Use Case:

  • Request-specific data like logging, metadata, or request IDs

4. 📥 Session Scope

One instance per HTTP session. Useful for storing session-based data like shopping carts.

📌 Example

@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class UserSession {
    private String username;
    // getters and setters
}
@RestController
public class SessionController {
    @Autowired
    private UserSession userSession;

    @GetMapping("/set")
    public String setUser() {
        userSession.setUsername("ramesh");
        return "Session user set!";
    }

    @GetMapping("/get")
    public String getUser() {
        return "Hello, " + userSession.getUsername();
    }
}

✅ Use Case:

  • Shopping cart
  • Logged-in user details
  • Preferences

5. 🌍 Application Scope

A single bean is shared across the entire web application, just like ServletContext.

📌 Example

@Component
@Scope(value = WebApplicationContext.SCOPE_APPLICATION)
public class AppWideCache {
    private final Map<String, Object> data = new HashMap<>();
}

✅ Use Case:

  • Shared app-wide cache
  • Application-level counters or stats

6. 🧩 WebSocket Scope

A separate bean is created for each WebSocket session.

📌 Example

@Component
@Scope(value = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class WebSocketSessionBean {
    private final String id = UUID.randomUUID().toString();
    public String getId() { return id; }
}

Requires Spring WebSocket and additional setup in configuration.


🧠 Best Practices

Rule Reason
Use singleton for stateless beans It’s efficient and simple
Use prototype carefully Doesn’t play well when injected into singleton
Always use proxyMode for web scopes Spring manages them behind proxies
Use @Scope on @Component or @Bean To declare scope at class or method level
Avoid custom scopes unless needed Increases complexity

🧪 Testing Bean Scope

You can verify scope behavior like this:

@Bean
@Scope("prototype")
public MyBean myBean() {
    return new MyBean();
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class ScopeTest {

    @Autowired
    private ApplicationContext context;

    @Test
    public void testPrototypeScope() {
        Object b1 = context.getBean("myBean");
        Object b2 = context.getBean("myBean");
        assertNotSame(b1, b2);
    }
}

✅ Summary Table

Scope Description Typical Use Case
singleton One instance per container Services, Repositories
prototype New instance per request Stateful helper objects
request New instance per HTTP request Request metadata, logs
session One instance per user session Shopping carts, user info
application Shared across application context Shared config, cache
websocket One per WebSocket session WebSocket connection info

✅ Final Thoughts

Understanding bean scopes helps you control when and how your Spring beans are created and shared. It’s a small configuration detail that has a big impact on your application's performance, state management, and memory usage.

Start with singleton by default, and reach for other scopes only when you have a real use case for stateful or context-aware beans.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare