Skip to lesson

Bean scopes and lifecycle callbacks

A shop site serves many customers at once. A price list can be shared by everyone, but a cart must never be. Spring needs to know which is which, and when to prepare and clean up each object.

Singleton, prototype, request and session scopes

A scope decides how many objects Spring makes from a bean and how long each one lives. Singleton, the default, gives one object for the whole app; prototype gives a new object every time the bean is requested.

PriceList is a singleton and ShoppingCart is a prototype. Ask the context for each twice and compare the objects.

Example 1 · PriceList.java, ShoppingCart.java, ScopeRunner.java

Runs in: the di-lab practice project (Spring Boot 4.1)

PriceList.javaJava
package com.shoplite.lab;
import org.springframework.stereotype.Component;
@Component   // singleton: the default scopepublic class PriceList {
    public PriceList() {        System.out.println("PriceList created");    }}
package com.shoplite.lab;
import java.util.ArrayList;import java.util.List;
import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Component;
@Component@Scope("prototype")   // a new object every time one is asked forpublic class ShoppingCart {
    private static int created = 0;
    private final int number;    private final List<String> items = new ArrayList<>();
    public ShoppingCart() {        created++;        number = created;        System.out.println("ShoppingCart #" + number + " created");    }
    public void add(String item) {        items.add(item);    }
    public String describe() {        return "cart #" + number + " " + items;    }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.ApplicationContext;import org.springframework.stereotype.Component;
@Componentpublic class ScopeRunner implements CommandLineRunner {
    private final ApplicationContext context;
    public ScopeRunner(ApplicationContext context) {        this.context = context;    }
    @Override    public void run(String... args) {        System.out.println("--- runner starts ---");        PriceList list1 = context.getBean(PriceList.class);        PriceList list2 = context.getBean(PriceList.class);        System.out.println("Same PriceList? " + (list1 == list2));
        ShoppingCart cart1 = context.getBean(ShoppingCart.class);        ShoppingCart cart2 = context.getBean(ShoppingCart.class);        System.out.println("Same ShoppingCart? " + (cart1 == cart2));    }}
Output
PriceList created
--- runner starts ---
Same PriceList? true
ShoppingCart #1 created
ShoppingCart #2 created
Same ShoppingCart? false

What this code does

  • PriceList is a singleton, so Spring creates it at startup, before the runner starts, and both getBean calls return that one object.
  • ShoppingCart is a prototype. Nothing creates it at startup; each getBean call creates a new one, numbered #1 and #2.
  • The static created counter only numbers the carts for this demo.

Web apps add two more. Request scope (@RequestScope) gives one object per HTTP request; session scope (@SessionScope) gives one object per user session, the period a browser stays logged in. They need Spring MVC, so they come with shoplite-api, not di-lab.

Almost every ShopLite bean is a singleton: controllers, services, repositories, configuration. Prototypes are rare, and request or session beans are rarer still, because a REST API passes per-user data in the request itself.

Singletons are shared: keep beans stateless

A stateless bean has no per-user data in its fields. Its fields hold only other beans and fixed settings, set once in the constructor, so many requests can use it at the same time.

Two customers use one CartTotalService whose fields hold a customer and a total. See what the shared fields do to their bills, then the fix.

Example 2 · CartTotalService.java, TwoUsersRunner.java

Runs in: the di-lab practice project (Spring Boot 4.1)

CartTotalService.javaJava
package com.shoplite.lab;
import org.springframework.stereotype.Service;
@Servicepublic class CartTotalService {
    // BUG: one shared bean, so these fields are shared by every user    private String customer;    private int total;
    public void startCart(String customer) {        this.customer = customer;        this.total = 0;    }
    public void add(int price) {        total += price;    }
    public String bill() {        return customer + " pays Rs " + total;    }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class TwoUsersRunner implements CommandLineRunner {
    private final CartTotalService service;
    public TwoUsersRunner(CartTotalService service) {        this.service = service;    }
    @Override    public void run(String... args) {        // Two requests arrive close together; their steps interleave        service.startCart("Asha");        service.add(1200);        service.startCart("Ravi");        service.add(300);         service.add(900);         System.out.println("Bill shown to Asha: " + service.bill());        System.out.println("Bill shown to Ravi: " + service.bill());    }}
Output
Bill shown to Asha: Ravi pays Rs 1200
Bill shown to Ravi: Ravi pays Rs 1200

What this code does

  • The runner plays two requests whose steps interleave, as real requests on two threads do. startCart("Ravi") resets the fields while Asha's cart is still open.
  • Asha is shown Ravi's name, and the Rs 1200 total mixes her dupatta with his headphones. Both bills are wrong, and no exception warns you.

Example 3 · Cart.java, CartTotalService.java, TwoUsersRunner.java

Runs in: the di-lab practice project (Spring Boot 4.1)

Cart.javaJava
package com.shoplite.lab;
import java.util.ArrayList;import java.util.List;
// Plain class, not a bean: one object per user, created by the callerpublic class Cart {
    private final String customer;    private final List<Integer> prices = new ArrayList<>();
    public Cart(String customer) {        this.customer = customer;    }
    public void add(int price) {        prices.add(price);    }
    public String customer() {        return customer;    }
    public List<Integer> prices() {        return prices;    }}
package com.shoplite.lab;
import org.springframework.stereotype.Service;
@Servicepublic class CartTotalService {
    // No fields that change: everything the method needs comes in as a parameter    public String bill(Cart cart) {        int total = 0;        for (int price : cart.prices()) {            total += price;        }        return cart.customer() + " pays Rs " + total;    }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class TwoUsersRunner implements CommandLineRunner {
    private final CartTotalService service;
    public TwoUsersRunner(CartTotalService service) {        this.service = service;    }
    @Override    public void run(String... args) {        Cart asha = new Cart("Asha");        asha.add(1200);        Cart ravi = new Cart("Ravi");        asha.add(300);        ravi.add(900);        System.out.println("Bill shown to Asha: " + service.bill(asha));        System.out.println("Bill shown to Ravi: " + service.bill(ravi));    }}
Output
Bill shown to Asha: Asha pays Rs 1500
Bill shown to Ravi: Ravi pays Rs 900

What this code does

  • Each customer has their own Cart object, a plain class created by the caller. The service has no changing fields and works only on the cart passed in.
  • The steps interleave exactly as before, yet both bills are right, because nothing per-user is stored in the shared bean.

A singleton bean is used by every request at the same time, and in a web app each request runs on its own thread. A field that stores one customer's data is overwritten by the other. The bug never shows up when you test alone and appears only under real traffic: one customer sees another's bill.

The rule: keep singleton beans stateless. Fields hold only other beans and fixed settings, set once in the constructor and marked final. Per-request data travels in method parameters, local variables and return values.

Find the bug

Find the shared state

Each service is a singleton used by many customers. Tap the wrong line.

Two customers add items at the same time.

Round 1 of 2
A shared counter that really belongs to the whole app (total visits, for example) is allowed, but it must be thread-safe, such as an AtomicInteger. The Multithreading section explains why.

The lifecycle: create, inject, initialise, use, destroy

The bean lifecycle is the fixed order of steps Spring takes a bean through: create, inject, initialise, use and destroy. A bean is created after the beans it depends on and destroyed before them.

StockCache needs AuditLog and loads its data after it is created. Run the app and read the numbered lines: they show the lifecycle in order.

Example 4 · AuditLog.java, StockCache.java, CacheRunner.java

Runs in: the di-lab practice project (Spring Boot 4.1)

AuditLog.javaJava
package com.shoplite.lab;
import org.springframework.stereotype.Component;
@Componentpublic class AuditLog {
    public AuditLog() {        System.out.println("1. AuditLog constructor");    }
    public void record(String event) {        System.out.println("   audit: " + event);    }}
package com.shoplite.lab;
import java.util.Map;
import jakarta.annotation.PostConstruct;import jakarta.annotation.PreDestroy;import org.springframework.stereotype.Component;
@Componentpublic class StockCache {
    private final AuditLog auditLog;    private Map<String, Integer> stockBySku = Map.of();
    public StockCache(AuditLog auditLog) {        this.auditLog = auditLog;        System.out.println("2. StockCache constructor, AuditLog injected");    }
    @PostConstruct    void load() {        stockBySku = Map.of("BOOK-101", 5, "PEN-007", 0, "MUG-12", 18);        System.out.println("3. @PostConstruct: loaded " + stockBySku.size() + " products");        auditLog.record("stock cache ready");    }
    public int stockOf(String sku) {        return stockBySku.getOrDefault(sku, 0);    }
    @PreDestroy    void clear() {        System.out.println("5. @PreDestroy: clearing the stock cache");    }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class CacheRunner implements CommandLineRunner {
    private final StockCache cache;
    public CacheRunner(StockCache cache) {        this.cache = cache;    }
    @Override    public void run(String... args) {        System.out.println("4. Runner uses the bean: MUG-12 stock = " + cache.stockOf("MUG-12"));    }}
Output
1. AuditLog constructor
2. StockCache constructor, AuditLog injected
3. @PostConstruct: loaded 3 products
   audit: stock cache ready
4. Runner uses the bean: MUG-12 stock = 18
5. @PreDestroy: clearing the stock cache

What this code does

  • StockCache needs AuditLog, so AuditLog is created first (1), then StockCache with the log injected (2), then its @PostConstruct method runs (3) and can already use the log.
  • The runner uses the ready bean (4). When run returns, di-lab has nothing left to do, the context closes and @PreDestroy runs (5). In a web app that happens when you stop the server, for example with Ctrl+C.
  • jakarta.annotation.PostConstruct and PreDestroy come with spring-boot-starter; no extra dependency is needed.

Every singleton bean goes through the same five steps:

  • Create: Spring calls the constructor, after creating the beans it needs.
  • Inject: dependencies are passed in (with constructor injection, in the same step).
  • Initialise: Spring calls the @PostConstruct method, if there is one.
  • Use: the bean is handed to other beans and runners.
  • Destroy: when the app shuts down, Spring calls the @PreDestroy method.

Order of execution

Order the bean lifecycle

Put the steps of a singleton bean in the order Spring runs them.

@PostConstruct and @PreDestroy

@PostConstruct marks a method Spring calls once, right after the bean is created and injected. @PreDestroy marks a method Spring calls when the context closes. Both come from jakarta.annotation.

Mark a loading method @PostConstruct and a cleaning method @PreDestroy. Mind the jakarta imports.

Java
import jakarta.annotation.PostConstruct;     // Spring Boot 3 and 4import jakarta.annotation.PreDestroy;// import javax.annotation.PostConstruct;  // old tutorials: does not compile here
@PostConstructvoid load() { ... }        // once, after creation and injection
@PreDestroyvoid clear() { ... }       // once, when the context closes

Use @PostConstruct for start-up work that needs the dependencies: load a small cache, or check a setting and fail fast if it is wrong. Use @PreDestroy to flush a buffer, close a connection or log a message.

Old tutorials import javax.annotation.PostConstruct; that package does not exist in Spring Boot 3 and 4, so the code does not compile. A prototype bean gets @PostConstruct, but never @PreDestroy: Spring hands the object over and stops tracking it, so whoever asked for it must clean it up.

Fix the error

Fix the import

Read the real error, then pick the line that fixes it.

The class is copied from an old tutorial.

import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;
@Component
public class StockCache {
@PostConstruct
void load() { }
}

Error

error: package javax.annotation does not exist

The prototype-inside-a-singleton trap

A prototype bean is a bean marked @Scope("prototype"): Spring creates a new object every time the bean is requested, and does not track or destroy it afterwards.

TrapDesk is a singleton that asks for a prototype ShoppingCart; FixedDesk asks for an ObjectProvider instead. Serve two customers with each and compare the cart numbers.

Example 5 · ShoppingCart.java, TrapDesk.java, FixedDesk.java, DeskRunner.java

Runs in: the di-lab practice project (Spring Boot 4.1)

ShoppingCart.javaJava
package com.shoplite.lab;
import java.util.ArrayList;import java.util.List;
import jakarta.annotation.PreDestroy;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Component;
@Component@Scope("prototype")public class ShoppingCart {
    private static int created = 0;
    private final int number;    private final List<String> items = new ArrayList<>();
    public ShoppingCart() {        created++;        number = created;    }
    public void add(String item) {        items.add(item);    }
    public String describe() {        return "cart #" + number + " " + items;    }
    @PreDestroy    void destroy() {        System.out.println("cart #" + number + " destroyed");   // never printed: see below    }}
package com.shoplite.lab;
import org.springframework.stereotype.Component;
@Componentpublic class TrapDesk {
    private final ShoppingCart cart;   // injected ONCE, when TrapDesk is created
    public TrapDesk(ShoppingCart cart) {        this.cart = cart;    }
    public String serve(String customer, String item) {        cart.add(item);        return customer + " gets " + cart.describe();    }}
package com.shoplite.lab;
import org.springframework.beans.factory.ObjectProvider;import org.springframework.stereotype.Component;
@Componentpublic class FixedDesk {
    private final ObjectProvider<ShoppingCart> carts;
    public FixedDesk(ObjectProvider<ShoppingCart> carts) {        this.carts = carts;    }
    public String serve(String customer, String item) {        ShoppingCart cart = carts.getObject();   // a fresh prototype on every call        cart.add(item);        return customer + " gets " + cart.describe();    }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class DeskRunner implements CommandLineRunner {
    private final TrapDesk trap;    private final FixedDesk fixed;
    public DeskRunner(TrapDesk trap, FixedDesk fixed) {        this.trap = trap;        this.fixed = fixed;    }
    @Override    public void run(String... args) {        System.out.println("Trap:  " + trap.serve("Asha", "Kurta"));        System.out.println("Trap:  " + trap.serve("Ravi", "Headphones"));        System.out.println("Fixed: " + fixed.serve("Asha", "Kurta"));        System.out.println("Fixed: " + fixed.serve("Ravi", "Headphones"));    }}
Output
Trap:  Asha gets cart #1 [Kurta]
Trap:  Ravi gets cart #1 [Kurta, Headphones]
Fixed: Asha gets cart #2 [Kurta]
Fixed: Ravi gets cart #3 [Headphones]

What this code does

  • TrapDesk got cart #1 when it was created and keeps it: Ravi receives Asha's cart with her kurta still in it.
  • FixedDesk calls carts.getObject() for each customer, so each one gets a new, empty cart (#2 and #3).
  • The cart's @PreDestroy method never prints, even when the app shuts down: Spring does not destroy prototype beans.

A singleton is created once, so it is injected once. If its constructor asks for a prototype bean, it receives one prototype object and keeps it forever, so every customer shares that "new" cart. The fix is to inject ObjectProvider<ShoppingCart> and call getObject() inside the method: every call returns a new prototype.

Ask first whether you need a prototype at all. Often a plain new Cart(customer) inside the method is simpler, because a cart holds data and needs no other beans.

Predict the output

Predict the cart

Choose what the code prints.

Round 1 of 2

TrapDesk is a singleton with a prototype ShoppingCart injected.

trap.serve("Asha", "Kurta");
String second = trap.serve("Ravi", "Headphones");
System.out.println(second);

Next step

Check your understanding

12 quick questions