The service created with new
A easy 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.
Highlighted: line 13. Play this one as a puzzle without the answer.
What is wrong
An object created with new is not managed by Spring, so its @Autowired fields are never injected. The repository is null and the first request throws NullPointerException. Annotations only work on beans the container creates.
The fix
How to avoid it next time
Receive collaborators through the constructor, and never call new on a Spring component.
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
Frequently asked questions
What is the bug in "The service created with new"?
An object created with new is not managed by Spring, so its @Autowired fields are never injected. The repository is null and the first request throws NullPointerException. Annotations only work on beans the container creates. The faulty line is line 13: private final PriceService service = new PriceService();
How do I fix it?
Replace it with: private final PriceService service; PriceController(PriceService service) { this.service = service; }. Receive collaborators through the constructor, and never call new on a Spring component.
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.