TExcelTAD
Home › Spring Boot › Bean Scopes & Lifecycle

Bean Scopes & Lifecycle

Every bean has a scope, which decides how many instances Spring creates, and a lifecycle, the sequence of steps from construction to destruction. Most of the time the defaults are exactly right, but you need to understand them to avoid subtle bugs — especially with shared state.

Scopes

Scope Instances Typical use
singleton (default) one per application context services, repositories, controllers
prototype a new one every time it is requested stateful helpers, builders
request one per HTTP request (web apps) per-request data
session one per HTTP session shopping cart in server-rendered apps
application one per ServletContext rarely needed
java
@Component
@Scope("prototype")             // or @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class ReportBuilder {
    private final StringBuilder sb = new StringBuilder();
    ReportBuilder line(String s) { sb.append(s).append('\n'); return this; }
    String build() { return sb.toString(); }
}

Here is the difference between the two main scopes, modelled in plain Java:

java · try it yourself
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

class Context {
    private final Map<String, Supplier<Object>> factories = new HashMap<>();
    private final Map<String, String> scopes = new HashMap<>();
    private final Map<String, Object> singletons = new HashMap<>();

    void define(String name, String scope, Supplier<Object> factory) {
        factories.put(name, factory);
        scopes.put(name, scope);
    }

    Object getBean(String name) {
        if (scopes.get(name).equals("prototype")) return factories.get(name).get();
        return singletons.computeIfAbsent(name, n -> factories.get(n).get());
    }
}

class Counter {
    private static int created = 0;
    final int id = ++created;
}

class Main {
    public static void main(String[] args) {
        Context ctx = new Context();
        ctx.define("shared", "singleton", Counter::new);
        ctx.define("fresh", "prototype", Counter::new);

        for (int i = 0; i < 3; i++) {
            Counter s = (Counter) ctx.getBean("shared");
            Counter p = (Counter) ctx.getBean("fresh");
            System.out.println("singleton #" + s.id + "   prototype #" + p.id);
        }
    }
}
singleton #1   prototype #2
singleton #1   prototype #3
singleton #1   prototype #4

Singletons must be thread-safe

A singleton controller serves every request, and Tomcat runs requests in parallel. Mutable instance fields in a singleton are therefore shared between users:

java
@RestController
class BadCounterController {
    private int count;                 // shared by all requests - race condition!

    @PostMapping("/hit")
    int hit() { return ++count; }
}

Keep singletons stateless (only final references to other beans), keep per-request data in local variables, and if you really need shared counters use thread-safe types such as AtomicInteger or ConcurrentHashMap.

The lifecycle

For a singleton bean, Spring performs these steps in order:

  1. Instantiate — call the constructor (constructor injection happens here).
  2. Populate — setter and field injection.
  3. Aware callbacks — e.g. BeanNameAware, ApplicationContextAware.
  4. @PostConstruct method — your initialisation code; all dependencies are ready.
  5. Proxying — post-processors may wrap the bean (this is how @Transactional works).
  6. In use while the application runs.
  7. @PreDestroy method — on shutdown, release resources.
java
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;

@Component
class PriceCache {
    private final PriceClient client;
    private final Map<String, Long> prices = new ConcurrentHashMap<>();

    PriceCache(PriceClient client) {
        this.client = client;
        System.out.println("1. constructor");
    }

    @PostConstruct
    void warmUp() {
        prices.putAll(client.fetchAll());
        System.out.println("2. warmed up with " + prices.size() + " prices");
    }

    @PreDestroy
    void close() {
        System.out.println("3. cache closed");
    }
}
bash · try it yourself
./mvnw -q spring-boot:run
# ... later, press Ctrl+C
1. constructor
2. warmed up with 3 prices
2025-10-16T09:30:12.004+07:00  INFO 50122 --- [tasks] [           main] com.example.tasks.TasksApplication       : Started TasksApplication in 1.912 seconds (process running for 2.240)
^C
3. cache closed

The same order, simulated by a minimal container that calls the hooks:

java · try it yourself
import java.util.ArrayList;
import java.util.List;

interface Lifecycle {
    default void postConstruct() {}
    default void preDestroy() {}
}

class PriceCache implements Lifecycle {
    PriceCache() { System.out.println("constructor"); }
    public void postConstruct() { System.out.println("@PostConstruct: load prices"); }
    public void preDestroy() { System.out.println("@PreDestroy: flush and close"); }
}

class AuditLog implements Lifecycle {
    AuditLog() { System.out.println("constructor (AuditLog)"); }
    public void preDestroy() { System.out.println("@PreDestroy (AuditLog)"); }
}

class Context {
    private final List<Lifecycle> beans = new ArrayList<>();
    void register(Lifecycle bean) {
        bean.postConstruct();
        beans.add(bean);
    }
    void close() {
        // destroy in reverse order of creation
        for (int i = beans.size() - 1; i >= 0; i--) beans.get(i).preDestroy();
    }
}

class Main {
    public static void main(String[] args) {
        Context ctx = new Context();
        ctx.register(new PriceCache());
        ctx.register(new AuditLog());
        System.out.println("-- application running --");
        ctx.close();
    }
}
constructor
@PostConstruct: load prices
constructor (AuditLog)
-- application running --
@PreDestroy (AuditLog)
@PreDestroy: flush and close

Spring also destroys singletons in reverse creation order, so a bean is always destroyed before the beans it depends on.

Note: @PreDestroy is not called for prototype beans — Spring hands them out and forgets them. If a prototype holds resources, the caller must clean up.

Lazy initialisation

Singletons are created eagerly at startup, so configuration errors surface immediately. Annotate a bean with @Lazy to create it on first use, or set spring.main.lazy-initialization=true to make all beans lazy (faster startup, but errors appear later at runtime).

Test yourself

What is the default scope of a Spring bean?

  1. prototype
  2. request
  3. singleton
  4. session

When does a @PostConstruct method run?

  1. Before the constructor
  2. After dependencies are injected, before the bean is used
  3. On every HTTP request
  4. At application shutdown

Why is a mutable int count field in a @RestController dangerous?

  1. Controllers cannot have fields
  2. The singleton is shared by concurrent requests, causing race conditions
  3. Spring resets it on every request
  4. It breaks JSON serialisation