🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment