Bean scopes
- Key idea
- The scope says how many instances of a bean the container creates and how long they live. Singleton (the default) is one per container; prototype, a new one each time it's requested; request and session, one per HTTP request or session.
- In the box
- The box leaderboard is one for everybody, but each athlete needs their own timer. Choose each bean's scope, find out why a prototype inside a singleton freezes and how ObjectProvider, @Lookup and scoped proxies fix it.
The athlete sends record() to Leaderboard, highlighted inside the context: a single shared leaderboard.
Three timers, WodTimer #1, #2 and #3, highlighted in amber: each request to the container creates a new one.
The three timers are still in the context, not highlighted: when the container closes, none of them receives the destroy callback.
CoachBoard and WodTimer #1, highlighted. An only once packet goes from the timer to the singleton: it was injected a single time.
HeatService, highlighted, sends getObject() twice and gets two different timers, WodTimer #2 and #3, also highlighted.
LookupHeatService, highlighted, sends newTimer() twice and receives WodTimer #2 and WodTimer #3.
The athlete sends GET /api/trace to TraceController; the RequestTrace proxy, highlighted, passes id() to request 1's object. Request 2's object waits on the right.
LazyReport, highlighted in amber, appears in the context next to other beans: it's only created the first time someone asks for it.
Final view: CoachBoard, HeatService and TraceController on top, the three timers below and the RequestTrace proxy on the right.
Step 1 of 9
One leaderboard for everybody
Leaderboard stores each athlete's best time. There must be just one, shared by the whole box. That's the default behaviour: singleton.
- One instance per container, created at startup.
- Every bean that injects it gets the same one.
- Every request (and every thread) uses it at the same time.
Step 2 of 9
A timer for each athlete
The timer (WodTimer) is different: it stores when one particular athlete started. If it were a singleton, the second athlete would overwrite the first one's start time.
With @Scope("prototype") (or the constant ConfigurableBeanFactory.SCOPE_PROTOTYPE), the container creates a new instance every time someone asks for it, either with getBean() or by injecting it.
Step 3 of 9
Nobody cleans up prototypes
The test asks for two timers and checks they're different. Then it closes the context… and @PreDestroy isn't called on either of them.
For a prototype, the container creates the object, configures it (injects dependencies, calls @PostConstruct) and hands it to whoever asked. From then on it keeps no reference: it can't know when you'll stop using it.
Step 4 of 9
Trap: a prototype inside a singleton
CoachBoard is a singleton and receives a WodTimer through its constructor. It looks like each athlete will get their own timer, but no:
- Injection happens once, when
CoachBoardis created. - From then on,
timerForNextAthlete()always returns the same object.
The prototype scope means "a new one every time the container is asked", and the singleton only asked once.
Step 5 of 9
ObjectProvider: ask every time
HeatService doesn't inject a timer but an ObjectProvider<WodTimer>: a handle to ask the container for timers whenever it wants.
Each timers.getObject() is a miniature getBean(), so every athlete gets a new one (#2, #3…). It also has getIfAvailable() and getIfUnique() for optional dependencies.
Step 6 of 9
@Lookup: method injection
Another way, without Spring's API in your code: declare a method (it can be abstract) returning the type you want and annotate it with @Lookup.
Spring generates a subclass (CGLIB again) that implements that method so it calls getBean(WodTimer.class) every time. It's called method injection.
Step 7 of 9
request and session: a proxy in front
In a web application there are scopes tied to HTTP: request (one per request), session (one per session), application (one per ServletContext).
RequestTrace is @RequestScope: each request has its own identifier. But TraceController is a singleton created at startup, when there's no request. What gets injected into it?
A proxy. @RequestScope is equivalent to @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS). The controller keeps the proxy and, on each call to id(), the proxy looks up the RequestTrace of the current request.
Step 8 of 9
@Lazy: create on first use
Singletons are created at startup, so errors show up early. But an expensive bean that's rarely used (a monthly report) can wait: @Lazy delays its creation until someone asks for it.
@Lazydoesn't change the scope: it's still a singleton.- If another bean that is not lazy injects it, it's created at startup to satisfy the dependency… unless the injection point is also
@Lazy, in which case Spring injects a lazy proxy.
Step 9 of 9
Recap
- singleton (default): one per container, created at startup, shared; best without state.
- prototype: a new one per request to the container; Spring doesn't destroy it.
- request / session / application: web only, and with a proxy if injected into something longer-lived.
- Prototype in a singleton: it freezes. Fixes:
ObjectProvider/Provider,@Lookup, scoped proxy. @Lazy: same scope, created on first use.
Code
Leaderboard.java
@Component // singleton by default: ONE leaderboard shared by every athlete and every thread
public class Leaderboard {
private final Map<String, Duration> best = new ConcurrentHashMap<>(); // shared state: thread-safe map
public void record(String athlete, Duration time) {
best.merge(athlete, time, (a, b) -> a.compareTo(b) <= 0 ? a : b);
}
public Map<String, Duration> standings() {
return Map.copyOf(best);
}
}WodTimer.java
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) // = @Scope("prototype"): a new timer every time one is asked for
public class WodTimer {
public static final AtomicInteger CREATED = new AtomicInteger();
public static final AtomicInteger DESTROYED = new AtomicInteger();
private final int number = CREATED.incrementAndGet();
private long startedAt; // state that belongs to ONE athlete
public void start(long nowMillis) {
startedAt = nowMillis;
}
public Duration stop(long nowMillis) {
return Duration.ofMillis(nowMillis - startedAt);
}
public int number() {
return number;
}
@PreDestroy
void cleanUp() {
DESTROYED.incrementAndGet(); // never called for prototypes
}
}ScopesTest.java
@Test
void aPrototypeIsNewEveryTimeAndNeverDestroyed() {
int destroyedBefore = WodTimer.DESTROYED.get();
try (var ctx = new AnnotationConfigApplicationContext(WodTimer.class)) {
WodTimer a = ctx.getBean(WodTimer.class);
WodTimer b = ctx.getBean(WodTimer.class);
assertThat(a).isNotSameAs(b);
} // close(): destroys the singletons only
assertThat(WodTimer.DESTROYED.get()).isEqualTo(destroyedBefore); // no @PreDestroy for prototypes
}CoachBoard.java
@Component
public class CoachBoard {
private final WodTimer timer; // injected ONCE, when the singleton is created
public CoachBoard(WodTimer timer) {
this.timer = timer;
}
public WodTimer timerForNextAthlete() {
return timer; // ⚠ always the same "prototype"
}
}HeatService.java
@Service
public class HeatService {
private final ObjectProvider<WodTimer> timers; // a factory handle, not a timer
public HeatService(ObjectProvider<WodTimer> timers) {
this.timers = timers;
}
public WodTimer timerForNextAthlete() {
return timers.getObject(); // asks the container each time: a new prototype
}
}LookupHeatService.java
@Service
public abstract class LookupHeatService {
@Lookup // Spring overrides this method (CGLIB) to return getBean(WodTimer.class)
protected abstract WodTimer newTimer();
public WodTimer timerForNextAthlete() {
return newTimer();
}
}RequestTrace.java
@Component
@RequestScope // = @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestTrace {
private final String id = UUID.randomUUID().toString(); // one per HTTP request
public String id() {
return id;
}
}LazyTest.java
@Test
void aLazySingletonWaitsForTheFirstRequest() {
LazyReport.CREATED.set(false);
try (var ctx = new AnnotationConfigApplicationContext(LazyReport.class)) {
assertThat(LazyReport.CREATED).isFalse(); // the context is up, the report isn't
ctx.getBean(LazyReport.class);
assertThat(LazyReport.CREATED).isTrue(); // created on first use
}
}HeatService.java
@Service
public class HeatService {
private final ObjectProvider<WodTimer> timers; // a factory handle, not a timer
public HeatService(ObjectProvider<WodTimer> timers) {
this.timers = timers;
}
public WodTimer timerForNextAthlete() {
return timers.getObject(); // asks the container each time: a new prototype
}
}