Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 66 ยท Inversion of Control and Beans

Bean Scopes and Lifecycle

How long Spring beans live and what happens when: singleton and prototype scopes, @PostConstruct and @PreDestroy, SmartLifecycle phases and startup order.

Two questions decide how a bean behaves: how many instances exist, and when they are created, started and destroyed. The first is the bean's scope. The second is its lifecycle. Getting them wrong causes classic bugs: shared state leaking between users, a connection used before it is ready, or a resource never released on shutdown.

This lesson covers the scopes you will actually use, the order of the lifecycle callbacks, and SmartLifecycle for components that must start and stop in a specific order. Real Spring code is read-only here. The two TryIt examples are plain-Java simulations of the same rules, and each says what is imitation.

Scopes

The default scope is singleton: the container creates one instance per bean definition and hands the same object to everyone. It is also created eagerly, when the context starts, so wiring errors show up at startup rather than on the first request.

Scopes you will meet

singleton One shared instance. The default.
prototype A new instance every time it is requested.
request One per HTTP request. Web apps only.
session One per HTTP session. Web apps only.

application and websocket scopes also exist, but are rare.

1 / 2

You pick a scope with @Scope:

Java
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)   // the string "prototype"
public class ReportBuilder {
    private final StringBuilder text = new StringBuilder();
    // state is fine here: every caller gets a private instance
}

A prototype bean is created each time it is asked for, by getBean, by injection or through an ObjectProvider. The container creates and wires it, then lets go: it does not track prototypes, so it never calls their destroy callbacks. Releasing their resources is your job.

Request and session scopes belong to web applications, and each instance lives as long as the request or session. They are useful for per-request data such as the current user context, but they cannot be injected directly into a singleton, because the singleton is built long before any request exists.

The singleton that needs a shorter-lived bean

Injecting a prototype or request bean into a singleton looks fine and quietly fails: injection happens once, so the singleton keeps the first instance forever. There are two clean fixes:

Java
@Component
public class ReportService {

    private final ObjectProvider<ReportBuilder> builders;

    public ReportService(ObjectProvider<ReportBuilder> builders) {
        this.builders = builders;
    }

    public String report() {
        ReportBuilder builder = builders.getObject();   // fresh instance each call
        ...
    }
}

ObjectProvider asks the container at call time, so you get the scope you declared. The second fix is a scoped proxy: @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS) injects a small stand-in object that looks up the real request bean on every call. Use ObjectProvider when you want to be explicit, and the proxy when you want the code to read like a normal injection.

The web scopes and custom scopes

Besides singleton and prototype, a web application has scopes tied to the servlet or WebSocket lifecycle:

Scope One instance per Shortcut annotation
request HTTP request @RequestScope
session HTTP session (one user's browser session) @SessionScope
application ServletContext, so one per web application @ApplicationScope
websocket WebSocket session @Scope("websocket")

The three shortcut annotations also set proxyMode = TARGET_CLASS, so they can be injected into singletons right away. The application scope looks like a singleton, but a singleton lives in one ApplicationContext while an application-scoped bean lives in the ServletContext; in a normal Boot application the difference is invisible.

A scope in Spring is an object that implements the org.springframework.beans.factory.config.Scope interface. The container asks it for a bean whenever a bean of that scope is needed. The five methods are:

Method Job
get(name, objectFactory) Return the existing instance for the current context, or ask objectFactory to create one and remember it
remove(name) Forget the instance and return it (or null)
registerDestructionCallback(name, callback) Remember a callback to run when the scope ends
resolveContextualObject(key) Provide contextual values such as the current request (may return null)
getConversationId() An id for the current context, such as a session id (may return null)

Registering a custom scope takes one bean. CustomScopeConfigurer is a BeanFactoryPostProcessor, so declare it with a static method (see Bean Configuration):

Java
@Configuration
class ScopeConfig {

    @Bean
    static CustomScopeConfigurer customScopes() {
        var configurer = new CustomScopeConfigurer();
        configurer.addScope("thread", new SimpleThreadScope());   // ships with Spring
        configurer.addScope("tenant", new TenantScope());         // your own
        return configurer;
    }
}

@Component
@Scope(value = "tenant", proxyMode = ScopedProxyMode.TARGET_CLASS)
class TenantSettings { /* ... */ }

Spring includes SimpleThreadScope but does not register it by default; it gives each thread its own instance and does not run destruction callbacks. You can also register a scope programmatically with beanFactory.registerScope("tenant", new TenantScope()).

Two warnings. First, a bean in a custom scope that is injected into a singleton needs a scoped proxy for the same reason as request-scoped beans: otherwise the singleton keeps whichever instance existed at injection time. Second, thread scope and thread pools mix badly: pool threads are reused, so "per thread" state leaks from one task to the next unless you clear it.

The stand-in below rebuilds the mechanism: a small Scope interface with the same get/remove contract, a container that hands out beans through the scope, and a thread scope that gives each thread its own instance.

Java A custom thread scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each thread keeps one instance for its whole life, and the two threads never share one, which is what SimpleThreadScope does. The Spring Scope interface works the same way; it only has more methods for cleanup and context information.

The lifecycle of one bean

A singleton goes through a fixed sequence between "the container decides to create it" and "the container closes". These are the steps you can hook into, in order:

sequenceDiagram
    participant C as Container
    participant B as Your bean
    C->>B: 1. constructor (dependencies injected)
    C->>B: 2. setters and field injection
    C->>B: 3. @PostConstruct
    C->>B: 4. afterPropertiesSet() (InitializingBean)
    C->>B: 5. custom init method (@Bean initMethod)
    Note over B: bean is ready and in use
    C->>B: 6. @PreDestroy
    C->>B: 7. destroy() (DisposableBean)
    C->>B: 8. custom destroy method

Creation runs top to bottom on startup; destruction runs when the context closes.

Between steps, BeanPostProcessor objects get a look at every bean. That is where @PostConstruct is actually handled, and where proxies for @Transactional and @Cacheable are created, which is why those annotations only work on beans the container manages.

In practice you use one of them:

Java
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;

@Component
public class PriceCache {

    private final PriceClient client;
    private Map<String, Integer> prices;

    public PriceCache(PriceClient client) {
        this.client = client;
    }

    @PostConstruct
    void load() {                 // dependencies are ready here
        prices = client.fetchAll();
    }

    @PreDestroy
    void flush() {                // called on context close
        prices = null;
    }
}

Prefer constructors for wiring and @PostConstruct only for work that needs a fully built bean. The interfaces InitializingBean and DisposableBean do the same job but tie your code to Spring, so annotations or @Bean(initMethod = ...) are the modern choice. Note the package: since Spring 6 and Boot 3 the annotations come from jakarta.annotation, not javax.annotation.

Keep @PostConstruct short. The context is not fully started while it runs, so calling other beans' web endpoints or doing long retries there delays the whole startup and blocks readiness.

The next TryIt simulates this sequence. It reads our own @Init and @Destroy annotations by reflection and runs them in order. It also counts instances to show singleton versus prototype.

Java Lifecycle and scope simulation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: the order (constructor, init callback, use, destroy callback), singletons being shared, and the container not destroying prototypes. What is the stand-in: real Spring supports many more hooks and runs them through BeanPostProcessor objects, not a loop.

Lazy initialization

Singletons are created at startup, which finds mistakes early. @Lazy on a bean (or spring.main.lazy-initialization=true for the whole application) delays creation until first use. That shortens startup time, but a broken bean now fails on its first request instead of at boot, and the first request pays the creation cost. Treat it as a deliberate trade-off, not a default.

SmartLifecycle: start and stop in order

Some components do more than initialize: they run. A message listener that consumes from a queue, a scheduler, a gRPC server. For those, implement SmartLifecycle:

Java
import org.springframework.context.SmartLifecycle;

@Component
public class QueueConsumer implements SmartLifecycle {

    private volatile boolean running;

    @Override
    public void start() {
        running = true;           // begin consuming
    }

    @Override
    public void stop() {
        running = false;          // finish in-flight work, stop consuming
    }

    @Override
    public boolean isRunning() {
        return running;
    }

    @Override
    public int getPhase() {
        return 100;               // higher phase = starts later, stops earlier
    }
}

All SmartLifecycle beans start automatically once the singletons exist (isAutoStartup() defaults to true). The phase decides the order: lower phases start first, and shutdown runs in the reverse order, so the thing that started last stops first. That is what you want: a consumer (phase 100) should stop accepting work before the database pool (a lower phase) closes.

In Boot the embedded web server follows the same idea. It starts late and stops early on graceful shutdown, so in-flight requests finish before beans are destroyed.

Java Phases: start in order, stop in reverse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Beans that share a phase (the consumer and scheduler here) start in the order the sort leaves them, which is their registration order. Do not rely on an order between equal phases: give them different phases if the order matters. The simulation is the real rule in miniature; the real container groups beans by phase and can stop a phase's beans in parallel with a timeout (spring.lifecycle.timeout-per-shutdown-phase).

Startup order between beans

You never choose the order in which singletons are created, only the dependencies between them. If B takes A in its constructor, A is created first. If two beans are unrelated, no order is guaranteed. When a bean must come up after another that it does not inject, use @DependsOn("other"), but treat it as a code smell and prefer a real dependency. If you need order for running work, use SmartLifecycle phases, or the ApplicationRunner ordering you will see in Application Events and Runners.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A singleton bean receives an injected prototype bean in its constructor. How many prototype instances does the singleton see?

    Injection happens once. To get a fresh instance each time, inject an ObjectProvider (or use a scoped proxy) and ask it when you need an instance.
  2. 2. In what order do these steps run when a bean is created?

    The constructor runs first (with its dependencies), then any setter or field injection, and only then the @PostConstruct callback.
  3. 3. Which statement about prototype beans and destruction is true?

    Spring creates and wires a prototype, then hands it over. Cleaning up its resources is the caller's responsibility.
  4. 4. Three SmartLifecycle beans have phases 0, 100 and 1000. How do they stop?

    Startup goes from the lowest phase to the highest, and shutdown runs in the reverse order, so what started last stops first.

Summary

  • The default scope is singleton: one shared instance, created at startup. Keep singletons stateless.
  • Prototype creates a new instance per request for the bean; the container does not destroy it. Request and session scopes belong to web applications.
  • To use a shorter-lived bean inside a singleton, inject an ObjectProvider or a scoped proxy.
  • Lifecycle order: constructor, injection, @PostConstruct, in use, @PreDestroy (annotations come from jakarta.annotation).
  • SmartLifecycle starts components in ascending phase order and stops them in the reverse order.
  • @Lazy and lazy initialization trade early error detection for startup speed.

Next: Qualifiers, @Primary and Collections.