0 day streak
java / intermediate
Snippet

Isolating Per-Request State Using Scoped Proxy Target Classes in Custom Context Holders

When working with multitenant architectures, injecting request-specific metadata into singleton beans can lead to race conditions and memory cross-contamination. By using `@RequestScope` with `ScopedProxyMode.TARGET_CLASS`, Spring injects a CGLIB dynamic proxy into singleton collaborators, lazily resolving the actual tenant data bound to the active HTTP thread's request lifecycle.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Component
@RequestScope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public class TenantContextHolder {
private String tenantId;
private String correlationId;
public void initialize(String tenantId, String correlationId) {
this.tenantId = tenantId;
this.correlationId = correlationId;
}
public String getTenantId() {
return this.tenantId;
}
public String getCorrelationId() {
return this.correlationId;
}
}
spring
Breakdown
1
@RequestScope(proxyMode = ScopedProxyMode.TARGET_CLASS)
Scopes the bean lifecycle to a single HTTP request and creates a CGLIB subclass proxy so singleton beans can safely inject it.
2
public void initialize(String tenantId, String correlationId) {
Populates the tenant and correlation metadata, typically invoked early by an interceptor or filter.
3
public String getTenantId() {
Accesses the tenant identifier resolved dynamically for the thread executing the current request.