빈 범위
싱글턴, 프로토타입, 요청, 세션 범위를 알아보세요.
빈 범위은(는) CoddyKit의 무료 Spring Boot 4 Microservices & REST APIs 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Microservices & REST APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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
자주 묻는 질문
“빈 범위” 강의는 무료인가요?
네 — “빈 범위” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Microservices & REST APIs 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
“빈 범위”에서 뭘 배우나요?
싱글턴, 프로토타입, 요청, 세션 범위를 알아보세요. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Microservices & REST APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Spring Boot 4 Microservices & REST APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Microservices & REST APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“빈 범위” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Spring Boot 4 Microservices & REST APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Spring Boot 4 Microservices & REST APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.