Bean-Scopes
Scopes für Singleton, Prototype, Request und Session.
Bean-Scopes ist eine kostenlose Spring Boot 4 Microservices & REST APIs-Lektion auf CoddyKit. Dies ist Lektion 3 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Spring Boot 4 Microservices & REST APIs-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Spring Boot 4 Microservices & REST APIs-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
What a Scope Controls
A bean’s scope determines how many instances the container creates and how long each lives. The default and most common scope is singleton.
Choosing the right scope matters for state, memory, and thread safety.
Singleton Scope
With singleton scope, the container creates exactly one instance per ApplicationContext and returns it for every injection point. This is ideal for stateless services.
@Service // singleton by default
public class PricingService {
public BigDecimal price(Order o) { /* stateless */ }
}Singletons Must Be Thread-Safe
Because one singleton serves all concurrent requests, it must not hold mutable per-request state in fields. Keep singletons stateless, or guard shared state carefully.
- Good: read-only config, injected collaborators
- Bad: a mutable field updated per request
Prototype Scope
Prototype scope creates a new instance every time the bean is requested or injected. Use it for stateful, short-lived helpers that should not be shared.
@Component
@Scope("prototype")
public class ReportBuilder {
private final List<String> rows = new ArrayList<>();
public void addRow(String r) { rows.add(r); }
}The Prototype-in-Singleton Trap
If you inject a prototype into a singleton via the constructor, you get one instance, captured once — not a fresh one per use. The singleton is built only once, so the prototype is resolved only once.
Getting Fresh Prototypes
To obtain a new prototype each time inside a singleton, inject an ObjectProvider (or a lookup) and call it on demand.
@Service
public class ReportService {
private final ObjectProvider<ReportBuilder> builders;
public ReportService(ObjectProvider<ReportBuilder> builders) {
this.builders = builders;
}
public Report build() {
ReportBuilder rb = builders.getObject(); // fresh each call
return rb.toReport();
}
}Web Scopes Overview
In a web application, two extra scopes tie a bean’s lifetime to an HTTP interaction: request and session. They exist only while a request or session is active.
Request Scope
A request-scoped bean is created once per HTTP request and discarded when it completes. Useful for per-request context like a correlation id or accumulated request data.
@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestContext {
private String correlationId;
// getters/setters
}Session Scope
A session-scoped bean lives for the duration of a user’s HTTP session, holding per-user state across multiple requests, such as a shopping cart in a server-rendered app.
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class UserCart {
private final List<Item> items = new ArrayList<>();
}Why Scoped Proxies
Injecting a short-lived scoped bean into a long-lived singleton needs a proxy. The proxy is injected once but delegates each call to the correct current-request or current-session instance.
That is why request/session beans use proxyMode = TARGET_CLASS.
Choosing a Scope
Guidelines:
- singleton — default; stateless shared services
- prototype — stateful, per-use helpers
- request — per-HTTP-request context
- session — per-user state across requests
Quick Check
Test your understanding of scopes.
Recap
Scope controls instance count and lifetime.
- singleton (default) — one per context, keep stateless
- prototype — new instance per request; beware the singleton trap
- request/session — web scopes needing scoped proxies
- Use
ObjectProviderfor fresh prototypes inside singletons
Häufig gestellte Fragen
Ist die Lektion „Bean-Scopes“ kostenlos?
Ja — der vollständige Text von „Bean-Scopes“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Spring Boot 4 Microservices & REST APIs-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Spring Boot 4 Microservices & REST APIs-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Bean-Scopes“?
Scopes für Singleton, Prototype, Request und Session. Du übst Spring Boot 4 Microservices & REST APIs mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Spring Boot 4 Microservices & REST APIs zu starten?
Keine Vorkenntnisse erforderlich. Spring Boot 4 Microservices & REST APIs auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 4.
Wie lange dauert die Lektion „Bean-Scopes“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Spring Boot 4 Microservices & REST APIs-Lektion Code schreiben und ausführen?
Ja. Jede Spring Boot 4 Microservices & REST APIs-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.