Skip to the workspace
Pebellslearn by building
The Spring Core  ›  Capstone Project

Spring Bean Scope — How Many Copies?

Spring Bean Scope 14 minA bean's scope decides how many instances exist; singletons are the default and shared by all requests, so they must not hold changing per-user state.

spring boot / Spring Bean Scope — How Many Copies?

Explore each scene at your own pace.

01 · The rule

The rule

Spring Bean Scope — How Many Copies?

A developer adds a field private int borrowCount; to LoanService to count one member's borrowings, and in testing it works. In production, members start seeing each other's counts. Nothing is wrong with the arithmetic. The bug is about how many LoanService objects exist, and that is what a bean's scope decides.

The rule

Singleton by default: one shared bean, so keep it stateless.

A bean's scope says how many instances the container creates and how long each lives.

Scope Instances Available in
singleton (default) One per application context, shared by everyone Any app
prototype A new one each time the bean is requested from the container Any app
request One per HTTP request Web apps
session One per HTTP session Web apps
application One per servlet context Web apps
@Component
@Scope("prototype")          // or @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class LoanReceiptBuilder {
    private final List<String> lines = new ArrayList<>();
    public void add(String line) { lines.add(line); }
}

Because a singleton is shared by every request, and a web server handles many requests at once on different threads, a singleton must not hold per-user or per-request data in its fields. Fields that hold collaborators (a repository, the settings) are fine because they never change after startup. That was the borrowCount bug: one field, one object, every member writing to it.

Almost every bean you write — controllers, services, repositories — should be a stateless singleton. Keep changing data in local variables, method parameters, or the database.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.