Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring session scope: one target across requests, separate targets across sessions

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A session-scoped proxy resolves state for the active HTTP session while a singleton service holds the proxy reference.

Download Spring source kit

The downloadable Spring source kit checks this boundary with the named JUnit test and its pinned dependencies.

Prove the lifetime with two sessions

The test binds two mock requests to the same session, then a third request to another session. The first counter returns one and two; the second starts at one. The service is still a singleton. The proxy changes which ReviewCounter instance receives each method call.

A session scope does not establish that the session belongs to an authenticated user. Session fixation, expiry, storage across nodes and tenant authorization need separate policies. Do not place unbounded receipt histories in a session-scoped bean.

Keep background work explicit

A worker without an active web request cannot assume this proxy will resolve to a session target. Pass a narrow authorized identifier or immutable command into background work. Request scope has a shorter lifetime and the same proxy-dispatch rule.

Checked source

Java
@Bean @SessionScope(proxyMode = ScopedProxyMode.TARGET_CLASS)
ReviewCounter reviewCounter() { return new ReviewCounter(); }
@Bean ReviewService reviewService(ReviewCounter counter) { return new ReviewService(counter); }

// The test binds two requests to session A, then one to session B.
assertEquals(1, viewInSession(service, first));
assertEquals(2, viewInSession(service, first));
assertEquals(1, viewInSession(service, second));

Verification boundary

SessionScopeBoundaryTest.retainsStateAcrossRequestsButNotAcrossSessions runs in the Spring source kit. This excerpt omits imports and surrounding test setup; the downloadable kit contains the complete source.

Costs and boundaries

The test checks local scope identity only. It does not exercise browser cookies, clustered session stores, concurrent requests sharing one session, session expiry, or any identity-provider integration.

Common Mistakes

  • Do not equate a session object with an authorized user.
  • Do not store unbounded application history in session memory.
  • Do not access the proxy from background work without an explicit context handoff.

Read next

Spring bean scopes: singleton identity is not thread safety, Spring request scope proxy: resolve state for the current HTTP request, Spring task executors: capacity, rejection and lost context.

spring
spring-boot
session-scope-boundary
Storage details