Sobes.tech
Senior

Where can request scope be useful?

sobes.tech AI

Answer from AI

Request scope in Java (for example, in Spring) is useful when you need to create a bean whose lifecycle is limited to a single HTTP request.

Examples of usage:

  • Storing data specific to the current request, such as user information, request parameters.
  • Caching intermediate results needed only within one request.
  • Managing transactions or sessions if they are tied to the request.

For example, if you have a service that collects statistics on the current request, you can make it request-scoped so that it does not create a new object for each call but also does not store data between requests.

In Spring, this is done as follows:

@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestScopedBean {
    // fields and methods
}

Thus, each HTTP request gets its own instance of this bean.