Skip to content
thesarfo

Concept

Spring Start Here: Bean Scopes

Singleton and prototype bean scopes, the web-specific request/session/application scopes, and a login-flow example that uses all three.

views 0

Spring manages a bean’s lifecycle differently depending on how you declare it in the Spring context. Every bean is one of:

  1. Singleton — the default bean scope; the framework uniquely identifies each instance with a name in the context.
  2. Prototype — the framework only manages the type, and creates a new instance every time someone requests it (directly from the context, or through wiring/autowiring).

In web apps, there are additional web scopes that only make sense for web applications:

  1. Request scope — Spring creates an instance for every HTTP request; the instance exists only for that specific request.
  2. Session scope — Spring creates an instance and keeps it in the server’s memory for the full HTTP session, linked to the client’s session.
  3. Application scope — the instance is unique across the app’s context, and available for as long as the app runs.

Understanding the web scopes

To see how these work together, consider implementing login functionality:

Step 1 — implement the login logic. If the user provides correct credentials, the app confirms a successful login. We don’t want Spring to keep the credentials in memory longer than the login request itself takes, so we use a request-scoped bean.

Step 2 — keep the logged-in user’s details. Once authenticated, we want to keep the user logged in for a while. We store their details using the HTTP session, through a session-scoped bean.

Step 3 — count login requests. Finally, we want to count all login requests from all users — the total needs to persist across the whole app. We use an application-scoped bean for that.