Real-World Analogy
`@Scope` specifies whether a rental car is shared by the whole company (Singleton) or rented individually per customer (Prototype).
Defining Bean Lifecycle Scope
`@Scope` specifies bean creation policy within IoC container.
Managing Bean Instance Lifecycles:
The @Scope annotation controls how often Spring creates new instances of a managed bean across the application lifecycle.
- Singleton Scope (Default): One single instance is shared across the entire application context.
- Prototype Scope: A new instance is created every single time the bean is requested from the container.
- Web Scopes: Request, Session, and Application scopes bind bean lifecycles directly to HTTP Web requests and user sessions.
Production Code Example:
package com.anujsingh.digitalguru.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class TokenBean {}
Key Architectural Concepts & Best Practices:
When working with @Scope 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 @Scope ensures that your Java & Spring Boot backend microservices remain maintainable, secure, and compliant with modern enterprise software engineering standards.
Default
Default scope is always `singleton`.