Video in progress
What happens if a prototype-scoped bean is injected into a singleton bean, and what's the right way to get a new instance each time?
The injection happens only once, when the singleton is created, so the prototype bean effectively becomes a single one too. To get a fresh one on every call, use ObjectProvider<T>, a @Lookup method or a scoped proxy.
📖 Answer
@Component
@Scope("prototype")
class CsvBatch { private final List<Row> rows = new ArrayList<>(); }
@Service
class ImportService {
private final CsvBatch batch; // one instance forever!
ImportService(CsvBatch batch) { this.batch = batch; }
}
The sign on prod: two parallel imports see each other's rows, and the list grows without stopping. Prototype doesn't mean "new for every request", it means "new every time it's requested from the container". The singleton only asked once.
Solutions:
@Service
class ImportService {
private final ObjectProvider<CsvBatch> batches;
ImportService(ObjectProvider<CsvBatch> batches) { this.batches = batches; }
void run(Path file) {
CsvBatch batch = batches.getObject(); // new every time
...
}
}
ObjectProvider<T>is the cleanest and easy to test; it also hasgetIfAvailable()andstream().@Lookup: Spring overrides an abstract method with CGLIB. It works, but it's more magical and the class has to be proxyable.@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS): every method call goes to a new instance. For a prototype this is almost always a mistake:batch.add()andbatch.size()land on different objects. A scoped proxy is meant forrequest/sessionscope.
One more thing: Spring doesn't manage the lifecycle of prototype beans, so @PreDestroy is not called for them. If they hold a resource, closing it is on you.
Often the question gets closed by this alone: does this thing have to be a Spring bean at all? If it has no dependencies, a plain new CsvBatch() is the simplest solution.
Sign up to mark studied questions and save your progress.