Senior
Întrebarea 7. Există un serviciu ExampleService (vezi imaginea). Dacă un serviciu extern apelează metodele în secvență: exampleService.getCityFromCache(100000); exampleService.getCity(100000); Cât de multe ori va fi apelat CityDao::getCity dacă cache-ul a fost gol? @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
Răspuns de la AI
В данном примере:
@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);
}
}
Вызовы:
exampleService.getCityFromCache(100000);
exampleService.getCity(100000);
Если кэш был пустым, то:
-
Первый вызов
getCityFromCache(100000)- Кэш пуст, вызывается
dao.getCity(100000), результат сохраняется в кэше.
- Кэш пуст, вызывается
-
Второй вызов
getCity(100000)- Внутри вызывается
getCityFromCache(100000). - Но вызов происходит внутри того же класса, поэтому Spring AOP-прокси не сработает, и аннотация
@Cacheableне применится. - Следовательно,
dao.getCity(100000)вызовется снова.
- Внутри вызывается
Итого: CityDao::getCity будет вызван 2 раза.
Это связано с тем, что Spring прокси применяет кэширование только при вызове метода через прокси (внешний вызов). Внутренние вызовы методов внутри одного класса не проходят через прокси и аннотации не срабатывают.