Sometimes a server needs to know something about a request it is handling: 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 scope defines how many instances of a bean 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 TenantContext {
var tenantId: String? = null
}Spring now creates a new TenantContext for every HTTP request and discards it when the request completes. Two simultaneous requests get two separate objects, so each can hold its own tenantId.
Injecting it into a singleton
Here is a 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 TenantContext should it receive?
@Service
class ReportService(private val tenantContext: TenantContext) {
fun title(): String = "Report for tenant ${tenantContext.tenantId}"
}Spring solves this with a scoped proxy. It doesn't inject a real TenantContext. 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 TenantContext that belongs to the current request and delegates the call to it.
Request A ─┐ ┌─> TenantContext (for A)
├─> ReportService ──> proxy ───────┤
Request B ─┘ (one instance) └─> TenantContext (for B)ReportService doesn't know that it holds a proxy. It is a singleton, but tenantContext.tenantId 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 a practical consequence for Kotlin. Spring creates the proxy by subclassing your class, so the class and its non-private members (functions and properties) must be open. Kotlin classes and members are final by default. Spring Boot projects normally use the kotlin-spring compiler plugin, which opens classes annotated with @Component, together with their members.
Without the plugin, a final class makes the application fail at startup. A final member is a quieter problem: the application starts, but calls to that member can't be intercepted. They run on the proxy object itself instead of being delegated to the instance of the current request, so a property like tenantId returns an empty value instead of the one from the request.
Filling the bean with data
Something has to put data into the request-scoped bean. There are several places to do it:
A controller or a service can set the value during the request, for example after it looks up the caller.
The bean can read the value itself from the
HttpServletRequest. Spring can inject the current request into a request-scoped bean, so this version takes the header when the bean is created for a request:
@Component
@RequestScope
class TenantContext(request: HttpServletRequest) {
val tenantId: String? = request.getHeader("X-Tenant-Id")
}An interceptor can fill it before any controller runs. This is useful when the same data is needed by all endpoints in a group, because the code lives in one place and can reject bad requests early.
Using an interceptor
An interceptor is 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 TenantInterceptor(private val tenantContext: TenantContext) : HandlerInterceptor {
override fun preHandle(
request: HttpServletRequest,
response: HttpServletResponse,
handler: Any,
): Boolean {
val tenantId = request.getHeader("X-Tenant-Id")
if (tenantId.isNullOrBlank()) {
response.status = HttpServletResponse.SC_BAD_REQUEST
return false // stop here: the controller is not called
}
tenantContext.tenantId = tenantId
return true // continue to the controller
}
}
@Configuration
class WebConfig(private val tenantInterceptor: TenantInterceptor) : WebMvcConfigurer {
override fun addInterceptors(registry: InterceptorRegistry) {
registry.addInterceptor(tenantInterceptor).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.
Writing error responses by hand in every interceptor gets repetitive. Instead, you can throw an exception from preHandle and turn it into a response in one place with a @RestControllerAdvice, the same way as for exceptions from controllers:
class MissingTenantException : RuntimeException("The X-Tenant-Id header is required")
@RestControllerAdvice
class ApiExceptionHandler {
@ExceptionHandler(MissingTenantException::class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
fun onMissingTenant(e: MissingTenantException) = mapOf("error" to e.message)
}With this handler, the if in preHandle becomes throw MissingTenantException(), and all error responses of your API keep the same shape.
Two cautions about interceptors. 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 TenantContext: the proxy delegates to the instance of the current request. The ReportService from above reads from the same instance when both run within the same request. So any bean that runs during a request can ask for TenantContext and see the caller's tenant, with the limits described in the next section.
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 a
ScopeNotActiveException, whose cause typically says that no thread-bound request was found.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
@Asyncmethod, 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 tenantId = tenantContext.tenantId // read on the request thread
executor.submit { process(tenantId) } // 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 tenantContext.tenantId 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. In Kotlin, the class and its non-private members must be open, which the kotlin-spring plugin takes care of. You can fill the bean from an interceptor, from the HttpServletRequest, or from controllers and services during the request.
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.