One common mistake which we should avoid while using @Async and @Cacheable in Spring boot

When solving performance bottlenecks first two things which come to our mind is parallelization and caching. And Spring boot provides out of the box feature like @Async and @Cacheable to do the same.

Okay, so let’s jump right into the topic

Self-invocation

Yep, this is the root cause. Both @Async and @Cacheable doesn’t work when they are called from within the same class.

Spring relies on Spring Proxy AOP to intercept calls to annotated methods like @Async or @Cacheable but when you call the underlying method directly it bypasses all the dynamic proxy and that’s the reason why these annotations doesn't do the job which it is supposed to do even though all the configuration is correct.

To resolve this issue, you can create a separate service which will have Async or Cacheable annotation and then call that service from the main service.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pratiyush Prakash

Full stack dev @ Texas Instruments. Follow me for short articles on software development. I will cover topics like Spring boot, Angular, SQL and so on.