Video in progress

Strong Middle 🌱 Spring

What happens if you inject a prototype bean into a singleton bean, and how do you solve it?

The singleton is created once and injection happens once, so it keeps that one prototype instance forever. If you need a fresh one each time, use ObjectProvider, a @Lookup method or a scoped proxy.

📖 Answer

@Component @Scope("prototype")
class ReportBuilder {            // stateful: collects lines
    private final List<String> lines = new ArrayList<>();
}

@Service
class ReportService {
    private final ReportBuilder builder; // one instance for all requests!
    ReportService(ReportBuilder builder) { this.builder = builder; }
}

As a result, reports from different users pile up in the same lines list.

The fix:

@Service
class ReportService {
    private final ObjectProvider<ReportBuilder> builders;

    Report build(...) {
        ReportBuilder b = builders.getObject(); // a new one on every call
        ...
    }
}
@Lookup
protected ReportBuilder newBuilder() { return null; } // Spring overrides this with CGLIB

There's also @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS), but then every method call lands on a new instance, which is usually not what you want.

Honestly, the simplest option is to not make the builder a bean at all: new ReportBuilder() or a factory bean. Spring doesn't have to manage a stateful, short-lived object.