Real-World Analogy
Think of a Singleton Bean like a public town clock—there is only ONE instance shared by everyone in town. Think of a Prototype Bean like a paper cup at a water cooler—a brand NEW cup is handed out every time someone asks for one!
Detailed Explanation of Bean Scopes
By default, every bean registered in the Spring IoC Container is a Singleton. Spring creates exactly one instance of the bean per container and injects that same shared instance everywhere.
Supported Spring Bean Scopes:
- Singleton (Default): One single bean instance per Spring IoC container. State must be thread-safe!
- Prototype: A new instance is created every time the bean is requested from the container.
- Request (Web): A new instance per HTTP request lifecycle.
- Session (Web): A new instance per HTTP Session lifecycle.
- Application (Web): One instance per ServletContext lifecycle.
Production Code Example:
package com.anujsingh.digitalguru.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import com.anujsingh.digitalguru.model.ShoppingCart;
@Configuration
public class AppConfig {
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public ShoppingCart shoppingCart() {
return new ShoppingCart();
}
}
Key Architectural Concepts & Best Practices:
When working with Spring Bean Scopes (Singleton vs Prototype) in enterprise Spring Boot applications, keep these key architectural guidelines in mind:
- Separation of Concerns: Maintain a strict boundary between HTTP endpoints, service logic, and database persistence layers.
- Framework Conventions: Rely on Spring Boot auto-configuration defaults whenever possible, overriding settings only via
application.ymlor@Configurationclasses when customized behavior is required. - Production Monitoring & Reliability: Ensure proper exception handling, thread-safety, and resource cleanup to prevent memory leaks and unexpected runtime downtime.
- Developer Ergonomics: Write clean, self-documenting code with modern Java features (Records, Lambdas, Streams) to simplify code reviews and maintenance.
Summary Takeaway:
Mastering Spring Bean Scopes (Singleton vs Prototype) ensures that your Java & Spring Boot backend microservices remain maintainable, secure, and compliant with modern enterprise software engineering standards.
Thread Safety Warning
Because Singleton beans are shared across concurrent user requests, NEVER store user-specific mutable state inside instance variables of `@Service` or `@RestController` singletons!