Sub topic 12
Prototype scope
This chapter assumes you know @Component, @Bean, constructor injection, and the singleton scope from the previous chapter. It also assumes you have seen the init and destroy callbacks. Here you will see how the prototype scope changes creation, injection and cleanup, and why it causes some of the most common scope bugs.
What prototype scope means
A bean with prototype scope is not cached. The container builds a new instance every time something asks for it. Asking means calling getBean(...), or resolving an injection point that needs the bean.
Declare it with @Scope:
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) // the string "prototype"
class Ticket { }Use prototype scope when an object holds state that belongs to one caller or one unit of work. Examples are a builder, a command object, or a stateful client that is not thread-safe. If the bean is stateless, keep it a singleton.
| Aspect | Singleton | Prototype |
|---|---|---|
| Instances per container | One per bean definition | One per request for the bean |
| Created | At startup (unless `@Lazy`) | Each time it is requested |
| Init callbacks | Once | Once per instance |
| Destroy callbacks | Called on context close | Never called by the container |
| Held by the container | Yes, in the singleton cache | No, after handing it over |
What the container does for each request
The container runs the full creation sequence for each request: instantiate, inject dependencies, run the Aware callbacks, run BeanPostProcessor hooks, and run the init callbacks. Then it hands the instance to the caller and forgets it.
Two consequences follow from this.
- Every dependency of the prototype is resolved at creation. A prototype that needs a singleton gets the shared singleton. A prototype that needs another prototype gets a new one.
- Prototype beans are never created at startup, so
@Lazyhas no effect on them. Spring may still check a prototype's definition at startup, but it creates no instance until one is requested.
The most common bug: a prototype injected once
Injection happens once, when the singleton is created. If a singleton has a prototype field, the singleton gets one instance and keeps it for its whole life. The bean is still a prototype, but nothing asks for a second instance.
This program shows the bug and the fix side by side:
package demo;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
class Ticket {
private static final AtomicInteger COUNTER = new AtomicInteger();
private final int number = COUNTER.incrementAndGet();
@PostConstruct
void init() {
System.out.println("init ticket " + number);
}
@PreDestroy
void cleanup() {
System.out.println("cleanup ticket " + number); // never printed
}
int number() {
return number;
}
}
@Component
class Desk {
private final Ticket injected;
private final ObjectProvider<Ticket> provider;
Desk(Ticket injected, ObjectProvider<Ticket> provider) {
this.injected = injected;
this.provider = provider;
}
void show() {
Ticket a = provider.getObject();
Ticket b = provider.getObject();
System.out.println("injected=" + injected.number()
+ " a=" + a.number() + " b=" + b.number()
+ " a==b: " + (a == b));
}
}
@Configuration
@ComponentScan
class AppConfig {
}
public class Main {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(AppConfig.class)) {
ctx.getBean(Desk.class).show();
}
}
}The output is:
init ticket 1
init ticket 2
init ticket 3
injected=1 a=2 b=3 a==b: falseTicket 1 was created while Desk was being built, and Desk keeps it forever. Tickets 2 and 3 were created on demand by the ObjectProvider. The cleanup line never appears, even though the context closes.
Ways to get a fresh instance each time
Pick one of these, in roughly this order of preference.
ObjectProvider<T>. It is a Spring type with no proxy involved.getObject()returns a new prototype each call.getObject(args...)passes constructor arguments, andgetIfAvailable()handles optional beans.jakarta.inject.Provider<T>. It has the same effect through the standard API, with onlyget().@Lookupmethod injection. You declare a method on a singleton, and Spring overrides it with a CGLIB subclass that callsgetBean. The class and the method cannot befinalorprivate.ApplicationContext.getBean(...). It works, but it ties your class to the container and makes testing harder. Avoid it in business code.- A scoped proxy. Use this only when you want per-call behavior, as the next section explains.
@Component
abstract class Printer {
@Lookup
protected abstract Ticket newTicket();
void print() {
System.out.println("ticket " + newTicket().number());
}
}Scoped proxies and prototypes
You can write @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS). The singleton then receives a proxy, and the proxy resolves a new prototype for every method call.
Destruction: why the container does not clean up
The container keeps singleton beans, so on context close it can find each one and call its destroy callbacks. It keeps no reference to a prototype, so it cannot find it later. The container also cannot know when you are finished with the object.
This affects the following:
@PreDestroyandDisposableBean.destroy()are ignored on prototypes.- A
destroyMethodon a prototype@Beanis ignored too. This includes the inferredcloseorshutdownthat Spring otherwise detects on@Beanmethods. - A
DestructionAwareBeanPostProcessornever getspostProcessBeforeDestructionfor prototypes. - The init side is unaffected.
@PostConstruct,afterPropertiesSet,initMethod, and theBeforeInitializationandAfterInitializationhooks all run for each new instance.
If a prototype holds a real resource, such as a file handle, a socket or a thread, whoever asks for it must release it. The simplest pattern is to close it in a try block where you use it. When a singleton creates many prototypes, it can track them and release them when it shuts down:
package demo;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
class Worker implements AutoCloseable {
@Override
public void close() {
System.out.println("worker closed");
}
}
@Component
class WorkerFactory implements DisposableBean {
private final ObjectProvider<Worker> provider;
private final List<Worker> created = new CopyOnWriteArrayList<>();
WorkerFactory(ObjectProvider<Worker> provider) {
this.provider = provider;
}
Worker create() {
Worker worker = provider.getObject();
created.add(worker);
return worker;
}
@Override
public void destroy() {
created.forEach(Worker::close);
created.clear();
}
}This pattern has a cost. The list keeps every worker reachable until shutdown, so a long-lived factory that creates many workers will leak memory. Remove a worker from the list when it is closed early, or use weak references if close-at-shutdown is only a safety net.
Edge cases
- Circular references. Spring resolves circular dependencies between singletons in some setups, but it cannot do so for prototypes. If prototype A needs prototype B and B needs A, creation fails with
BeanCurrentlyInCreationException. Break the cycle with anObjectProviderin one of them. - Constructor arguments.
ctx.getBean(Ticket.class, "vip")orprovider.getObject("vip")passes explicit arguments to the constructor. Spring matches them to the constructor parameters it cannot resolve itself. This works only for prototypes, since a singleton is built once. - Memory. Nothing in the container holds a prototype after it returns it, so the garbage collector can reclaim it once your code drops it. The leak risk is code you write, as in the tracking list above.
- Cost. Each request runs the whole creation sequence, including every post-processor. For hot paths, creating a plain object with
newcan be cheaper if it needs no injection.
Exercise
A singleton ReportService has a field private final ReportBuilder builder; injected by constructor. ReportBuilder is a prototype bean that keeps a list of rows added by each report. Users report that the rows from earlier reports show up in later ones. What is the cause, and how do you fix it? Also, the builder's @PreDestroy method never logs anything. Why?
Show answer
The singleton is created once, so Spring injects a single ReportBuilder into it once, and every report reuses that builder and its row list. Fix it by injecting ObjectProvider<ReportBuilder> and calling getObject() at the start of each report, so each report gets a new builder. @PreDestroy never runs because the container does not keep prototype instances and does not call destruction callbacks on them. If the builder owns a resource, the code that uses it must close it, for example with try-with-resources if it implements AutoCloseable.