A transactional private method
A medium 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 6. Play this one as a puzzle without the answer.
What is wrong
Spring AOP proxies intercept public calls that arrive from outside the bean. A private method cannot be proxied (and a self call would bypass the proxy anyway), so the annotation has no effect and no transaction is created.
The fix
How to avoid it next time
Put @Transactional on public methods called from other beans, and test the transaction boundary.
Want the background? Read @Transactional 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 "A transactional private method"?
Spring AOP proxies intercept public calls that arrive from outside the bean. A private method cannot be proxied (and a self call would bypass the proxy anyway), so the annotation has no effect and no transaction is created. The faulty line is line 6: @Transactional
How do I fix it?
Replace it with: @Transactional public void run() { post(1, 500); } // annotate the public entry point. Put @Transactional on public methods called from other beans, and test the transaction boundary.
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.