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 |
@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:
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:
@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:
- Instantiate — call the constructor (constructor injection happens here).
- Populate — setter and field injection.
- Aware callbacks — e.g.
BeanNameAware,ApplicationContextAware. @PostConstructmethod — your initialisation code; all dependencies are ready.- Proxying — post-processors may wrap the bean (this is how
@Transactionalworks). - In use while the application runs.
@PreDestroymethod — on shutdown, release resources.
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");
}
}./mvnw -q spring-boot:run
# ... later, press Ctrl+C1. 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:
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:
@PreDestroyis 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?
- prototype
- request
- singleton
- session
When does a @PostConstruct method run?
- Before the constructor
- After dependencies are injected, before the bean is used
- On every HTTP request
- At application shutdown
Why is a mutable int count field in a @RestController dangerous?
- Controllers cannot have fields
- The singleton is shared by concurrent requests, causing race conditions
- Spring resets it on every request
- It breaks JSON serialisation