Question situation:

A class has methods A and B, and when method A is called, the database is called every time. Not as expected.

A * * * * method/public Manager info () {return info (ManagerHelper. GetManagerId ()); } /** * B */ @Cacheable(key = "#id") public Manager Info (Long id) {return managerRepository.findById(id).orElseThrow(EntityExistsException::new); }

Cause of the problem:

Spring Cache Annotations are based on Spring AOP facets and must be proxied to take effect. When a call of the same class or a subclass calls a method of its parent class with a cached annotation, it is an internal call and does not take effect.

Solution:

One way is to pull the cached methods into a separate class and call them in the Service implementation class.

Approach two: manually use CacheManager to get the caching effect.

Conclusion:

  • Using annotations@CacheableThe object of must be a Spring-managed Bean.
  • The caller must be another method.

Annotated caching does not work in the following situations:

Within the same Bean, a subclass calls a method that has a cached annotation in its parent class