Sometimes a server needs to know something about the request it is handling right now: who is calling, which language they prefer, or a trace ID for the logs. You could pass that value through every function call, but that quickly gets tedious. A global variable doesn't work either, because the server handles many requests at the same time, and each has its own value.
Spring has a built-in solution: request-scoped beans. In this topic, you'll learn what bean scopes are, how a request-scoped bean works, why you can inject it into a singleton, and where its limits are.
Bean scopes
A bean's scope defines how many instances of it exist and how long they live. The default scope is singleton: Spring creates one instance when the application starts, and every other bean that needs it receives that same instance. Most of your services and controllers are singletons, and this is also why a singleton must never store data about one particular request. Two users calling at the same time would overwrite each other's data.
Spring offers other scopes:
Scope | Instances |
|---|---|
| one per application context |
| a new one every time the bean is requested |
| one per HTTP request |
| one per HTTP session |
| one per servlet context |
| one per WebSocket session |
The last four are called web scopes, and they require a web application. A Spring Boot web application has what they need, so no extra configuration is necessary.
A request-scoped bean
To make a bean request-scoped, add @RequestScope next to @Component:
@Component
@RequestScope
class ClientContext {
var clientId: String? = null
}Spring now creates a new ClientContext for every HTTP request and discards it when the request completes. Two simultaneous requests get two separate objects, so each can hold its own clientId.
Injecting it into a singleton
Here is the puzzle. A singleton service is created once, at startup, and its dependencies are injected at that moment. But at startup, there is no request yet, so which ClientContext should it receive?
@Service
class ChatService(private val clientContext: ClientContext) {
fun greet(): String = "Hello, ${clientContext.clientId}!"
}Spring solves this with a scoped proxy. It doesn't inject a real ClientContext. It injects a stand-in object that looks like one. Each time you call a method or read a property on the stand-in, it looks up the ClientContext that belongs to the current request and delegates the call to it.
Request A ─┐ ┌─> ClientContext (for A)
├─> ChatService ──> proxy ───────┤
Request B ─┘ (one instance) └─> ClientContext (for B)ChatService doesn't know that it holds a proxy. It is a singleton, but clientContext.clientId still returns the right value for each request.
You don't need to ask for the proxy: @RequestScope uses a class-based proxy by default. This has two practical consequences for Kotlin:
Spring creates the proxy by subclassing your class, so the class must be open. Kotlin classes are final by default. Spring Boot projects normally use the
kotlin-springcompiler plugin, which opens classes annotated with@Component. Without the plugin, you will get an error at startup.The proxy only intercepts calls to non-private members, so a private method would run on the proxy itself instead of on the real object.
If you'd rather not depend on a proxy, Spring offers alternatives. You can inject an ObjectProvider<ClientContext> and call getObject() when you need the instance, or you can inject HttpServletRequest, which is also request-scoped.
Filling the bean from an interceptor
Something has to put data into the request-scoped bean. A common place is an interceptor: a Spring MVC component that wraps the handling of a request. It can implement three callbacks:
preHandleruns before the controller;postHandleruns after the controller has handled the request;afterCompletionruns when the whole request has finished.
You register interceptors in a WebMvcConfigurer, and you can choose which paths they apply to. Here is a simplified example of an interceptor that reads a header:
@Component
class ClientIdInterceptor(private val clientContext: ClientContext) : HandlerInterceptor {
override fun preHandle(
request: HttpServletRequest,
response: HttpServletResponse,
handler: Any,
): Boolean {
val clientId = request.getHeader("X-Client-Id")
if (clientId.isNullOrBlank()) {
response.status = HttpServletResponse.SC_BAD_REQUEST
return false // stop here: the controller is not called
}
clientContext.clientId = clientId
return true // continue to the controller
}
}
@Configuration
class WebConfig(private val clientIdInterceptor: ClientIdInterceptor) : WebMvcConfigurer {
override fun addInterceptors(registry: InterceptorRegistry) {
registry.addInterceptor(clientIdInterceptor).addPathPatterns("/api/**")
}
}preHandle returns a Boolean. When it returns true, the request continues. When it returns false, the rest of the chain is skipped, and the interceptor must write the response itself. The addPathPatterns call limits the interceptor to matching paths, and excludePathPatterns removes some of them.
Two cautions from Spring's documentation: for controller methods that return the body directly, the response is already written by the time postHandle runs, so it is too late to change it there. And interceptors aren't a good fit for security checks, so use a dedicated mechanism such as Spring Security for that.
The interceptor is a singleton, yet it writes to the right ClientContext: the proxy delegates to the instance of the current request. The ChatService from above reads from the same instance, because both run within the same request. Any bean in the application can now ask for ClientContext and see the caller's ID.
Where it stops working
Outside a request. A request-scoped bean exists only while a request is being handled. Code that runs at startup, in a scheduled task, or in response to some other event has no current request. If it touches the bean, Spring throws an IllegalStateException, typically mentioning a missing thread-bound request or an inactive request scope.
On other threads. In Spring MVC, the current request is bound to the thread that handles it. If you hand work to another thread, such as an executor, an @Async method, or a coroutine on a different dispatcher, that thread doesn't see the request and fails in the same way. Read the value first and pass it as a normal argument:
val clientId = clientContext.clientId // read on the request thread
executor.submit { process(clientId) } // the other thread gets a plain valueFor sharing between requests. A new instance is created for every request, so a request-scoped bean can't remember anything between requests. For that, you need a different mechanism, such as a session-scoped bean or a store like a database or a cache.
A good habit
Treat the request-scoped bean as a place where the application receives data, not as a place to use it everywhere. Read clientContext.clientId at the edge, in a controller or a service method, and pass it as a parameter to the functions that do the work. Those functions are then plain Kotlin that you can test without a web context.
Conclusion
A bean's scope defines how many instances exist and for how long. Singletons are the default and are shared by all requests, so they must not hold per-request data. A @RequestScope bean is created for each HTTP request, and Spring injects a proxy into singletons that looks up the instance for the current request on every call. The usual way to fill it is an interceptor.
The bean only exists inside a request and only on the thread that handles it. Outside a request or on another thread, read the value first and pass it along explicitly.