cloudchamber's blog

Do not abuse recursion in Spring IoC Managed Bean

I was digging into Spring Cache Abstraction, especially using Spring Data Redis. To use @Cacheable annotation, I created Simple Fibonacci caculation Service. At first glance, Caching seem to be working well, but I found some unexpected behaviour in my method.
When I called fibo(n) I was expecting fibo::n, fibo::n-1, ..., fibo::0 all of those values are stored in redis but it isn't.
The root cause was simple, @Cacheable annotation works via Proxy Object, but in my recursive code I called function directly without using Proxy Object.
Solution is Simple, first, you can make your service aware of ApplicationContext, and using getBean method you get easily retrieve proxy object. but it has limitation that for each call, getBean method called and this could make your application do unnecessary job. Another solution is create a Self referencing field using @Lazy and @Autowired annotation. You can see the example, in the below link. ;)

source code