BackendBench
Coffee
Spot the Bug #95

A prototype bean that is created once

A hard Java puzzle in the spring pitfalls family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

hardSpring pitfallsbuggy line: 12

Highlighted: line 12. Play this one as a puzzle without the answer.

What is wrong

Spring injects dependencies once, when the singleton ReportService is created. The prototype scope only creates a new instance per injection, so the service holds one ReportBuilder forever, and every report is appended to the same buffer.

The fix

private final ObjectProvider<ReportBuilder> builders; ... ReportBuilder b = builders.getObject();

How to avoid it next time

To get a fresh prototype per use, inject ObjectProvider or use a scoped proxy; or avoid mutable beans entirely.

Want the background? Read Spring beans and dependency injection in the Java concepts library.

About spring pitfalls

Spring features such as @Transactional, @Async and @Cacheable work through proxies. Calls that bypass the proxy, wrong bean scopes and misplaced annotations make behavior silently disappear.

In code review: For every annotation that adds behavior, check that the call crosses a Spring-managed bean boundary, that the method is public, and that the bean is a singleton only when it is stateless.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #94#96 โ†’

Frequently asked questions

What is the bug in "A prototype bean that is created once"?

Spring injects dependencies once, when the singleton ReportService is created. The prototype scope only creates a new instance per injection, so the service holds one ReportBuilder forever, and every report is appended to the same buffer. The faulty line is line 12: @Autowired ReportBuilder builder;

How do I fix it?

Replace it with: private final ObjectProvider builders; ... ReportBuilder b = builders.getObject();. To get a fresh prototype per use, inject ObjectProvider or use a scoped proxy; or avoid mutable beans entirely.

How do I catch spring pitfalls in code review?

For every annotation that adds behavior, check that the call crosses a Spring-managed bean boundary, that the method is public, and that the bean is a singleton only when it is stateless.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need