Sobes.tech
Senior

Question 7. There is a service ExampleService (see figure). If an external service calls the following methods in sequence: exampleService.getCityFromCache(100000); exampleService.getCity(100000); How many times will there be a call to CityDao::getCity if the cache was empty? @Component @RequiredArgsConstructor public class ExampleService { private final CityDao dao; @Cacheable public String getCityFromCache(int index) { return dao.getCity(index); } public String getCity(int index) { return getCityFromCache(index); } }

sobes.tech AI

Answer from AI

In this example:

@Component
@RequiredArgsConstructor
public class ExampleService {

    private final CityDao dao;

    @Cacheable
    public String getCityFromCache(int index) {
        return dao.getCity(index);
    }

    public String getCity(int index) {
        return getCityFromCache(index);
    }

}

Calls:

exampleService.getCityFromCache(100000);
exampleService.getCity(100000);

If the cache was empty:

  • The first call getCityFromCache(100000)

    • The cache is empty, so dao.getCity(100000) is called, and the result is stored in the cache.
  • The second call getCity(100000)

    • Internally calls getCityFromCache(100000).
    • But the call occurs within the same class, so the Spring AOP proxy does not activate, and the @Cacheable annotation does not apply.
    • Therefore, dao.getCity(100000) is called again.

In total: CityDao::getCity will be called 2 times.

This is because Spring applies caching only when calling a method through the proxy (external call). Internal method calls within the same class do not go through the proxy, and annotations do not trigger.

Question 7. There is a service ExampleService (see… - sobes.tech