Sub topic 8
Proxy behavior and the self-invocation trap
This chapter assumes you know how Spring beans and dependency injection work, and that you have already used @Cacheable on a service method. Here you will learn why caching annotations only work on some calls, how to recognize the failure, and how to fix it.
Caching is applied by a proxy
Spring does not change the bytecode of your ProductService. When @EnableCaching is active, Spring wraps each bean that has caching annotations in a proxy. A proxy is an object that has the same public methods as your bean and sits in front of it. Other beans receive the proxy, not your original object.
When a caller invokes a cached method, the proxy runs a sequence of steps:
- The proxy looks for caching metadata on the called method.
- It computes the cache key and checks the cache.
- On a hit, it returns the stored value and never calls your method.
- On a miss, it calls your real method, stores the result, and returns it.
The caching logic lives in the proxy. Your method body only contains business logic. This keeps your code clean, but it creates one important rule: the cache only works for calls that pass through the proxy.
How Spring creates the proxy
Spring picks one of two proxy mechanisms.
| Mechanism | How it works | Typical use |
|---|---|---|
| JDK dynamic proxy | Implements the same interfaces as the target | Used when proxying is interface-based and proxy-target-class is off |
| CGLIB proxy | Generates a subclass of the target class at runtime | Default in Spring Boot |
Spring Boot sets spring.aop.proxy-target-class=true by default, so most beans are proxied with CGLIB. Two consequences follow from this:
- A CGLIB proxy overrides methods by subclassing. Therefore,
finalclasses cannot be proxied, andfinalmethods are not intercepted. A@Cacheableon afinalmethod is silently ignored. - Spring intercepts only
publicmethods by default with proxy-based caching. Annotating aprivateor package-private method has no effect in the default proxy mode.
You can check what you received by printing AopUtils.isAopProxy(service) or by looking at the class name. A CGLIB proxy has a name like ProductService$$SpringCGLIB$$0.
The self-invocation trap
The proxy sits between the caller and the target. Inside the target, though, this refers to the real object, not the proxy. When one method of a bean calls another method of the same bean, the call goes straight to this. It never touches the proxy, so no caching advice runs.
@Service
public class ReportService {
public String latestDailyReport() {
// Self-invocation: this call does not go through the Spring proxy,
// so the @Cacheable advice on load() is never applied.
return load("daily");
}
@Cacheable("reports")
public String load(String name) {
return "report:" + name;
}
}If a controller calls reportService.load("daily"), the proxy handles it and the result is cached. If the controller calls reportService.latestDailyReport(), the proxy forwards that call to the target. The target then calls this.load("daily") directly. Every call runs the full method body, and the cache stays empty.
The same limit applies to @CachePut and @CacheEvict. A self-invoked @CacheEvict method will delete from the store but leave the stale cache entry in place, which is worse than a missing cache because it causes wrong data.
How to recognize it
The failure is silent. There is no exception and no warning. Typical signs:
- A method you annotated is slow on every call.
cacheManager.getCache("reports")shows no entries after repeated calls.- A debug log of your method body (for example, a log line inside
load) prints on every call. - Actuator shows
cache.getscounters that do not move (see the later chapter on monitoring).
Fixing self-invocation
There are four common fixes. They differ in how much they change your design.
| Fix | Change required | Trade-off |
|---|---|---|
| Move the cached method to another bean | Extract a new `@Service` | Cleanest, and usually the best choice |
| Inject the proxy into itself | Self-reference with `@Lazy` | Works, but reads oddly and couples the class to its own proxy |
| Use `AopContext.currentProxy()` | Enable `exposeProxy` and cast | Ties business code to Spring AOP |
| Switch to AspectJ weaving | `@EnableCaching(mode = AdviceMode.ASPECTJ)` plus a weaver | Handles self-invocation, but adds build or runtime weaving setup |
Fix 1: extract another bean
Move the cached method into its own class. Callers then reach it through a proxy.
@Service
public class ReportLoader {
@Cacheable("reports")
public String load(String name) {
return "report:" + name;
}
}
@Service
public class ReportService {
private final ReportLoader loader;
public ReportService(ReportLoader loader) {
this.loader = loader;
}
public String latestDailyReport() {
// loader is a proxy, so the cache advice runs.
return loader.load("daily");
}
}This is the approach to prefer. It also gives each class a single job: one class decides which report to fetch, the other knows how to load and cache it.
Fix 2: inject the bean into itself
Spring can inject a proxy of a bean into the same bean if you mark the injection point @Lazy. Without @Lazy, the container fails with a circular reference.
@Service
public class ReportService {
private final ReportService self;
public ReportService(@Lazy ReportService self) {
this.self = self;
}
public String latestDailyReport() {
return self.load("daily");
}
@Cacheable("reports")
public String load(String name) {
return "report:" + name;
}
}This works, but a reader has to know why the class holds a reference to itself. Add a comment if you use it.
Fix 3 and 4: AopContext and AspectJ
AopContext.currentProxy() returns the proxy for the current call. It requires @EnableAspectJAutoProxy(exposeProxy = true), and it fails with an exception if the call does not come through a proxy. AspectJ mode weaves the advice into the class itself, so this.load(...) is intercepted too. It needs spring-aspects and a compile-time or load-time weaver. Choose it only if you have many such cases and cannot restructure the code.
Other situations where the proxy is bypassed
Self-invocation is the most common cause, but not the only one.
- Objects created with
new. Anew ReportService()is not a Spring bean, so it has no proxy. Always get the bean from the container. - Calls during construction. A call from a constructor or a
@PostConstructmethod may run before the proxy is fully set up, so caching can be skipped. - Non-public methods. As noted above, only public methods are advised in the default proxy mode.
finalclasses and methods. CGLIB cannot override them.- Annotations on interfaces. Place caching annotations on concrete classes. Annotations on interface methods work only with interface-based proxies, and that is not the Boot default.
Verifying the proxy behavior
You can prove the trap with a test that counts how often the method body runs. The test below uses a counter inside the service and a CacheManager check.
@Service
public class CountingReportService {
final AtomicInteger loads = new AtomicInteger();
public String viaSelf(String name) {
return load(name);
}
@Cacheable("reports")
public String load(String name) {
loads.incrementAndGet();
return "report:" + name;
}
}
@SpringBootTest
class SelfInvocationTest {
@Autowired
CountingReportService service;
@Test
void directCallIsCached() {
service.load("a");
service.load("a");
assertThat(service.loads.get()).isEqualTo(1);
}
@Test
void selfInvocationIsNotCached() {
service.viaSelf("b");
service.viaSelf("b");
assertThat(service.loads.get()).isEqualTo(2);
}
}Each test needs a fresh counter or a cleared cache if you run them in the same context. Use different keys, as above, or clear the reports cache in a @BeforeEach method. Note that the loads counter is shared across tests, so assertions that compare absolute values are fragile. Compare the difference before and after instead.
Summary of rules
- Caching advice runs in a proxy, so only calls from outside the bean are cached.
- A call to
this.method()inside the same bean skips the proxy. - Prefer extracting the cached method into a separate bean.
- Keep cached methods public and non-final, in non-final classes.
- Verify with a test that counts executions of the method body.
Exercise
A ProductService has a public method getPriceWithTax(Long id) that calls this.findById(id). findById is annotated with @Cacheable("products"). A controller calls getPriceWithTax(1L) ten times. How many times does the body of findById run, and what is the simplest fix?
Show answer
It runs ten times, because the call to findById is a self-invocation that bypasses the proxy, so no cache lookup happens. The simplest fix is to move findById into a separate @Service bean (for example ProductLoader), inject it into ProductService, and call it through the injected reference.
Exercise
You annotate a private method with @Cacheable and call it from a public method of the same bean. The application starts without errors, yet nothing is cached. Give two reasons the cache is bypassed.
Show answer
First, the call is a self-invocation, so it does not pass through the proxy. Second, proxy-based caching only intercepts public methods, so the annotation on a private method is ignored even if the call came from outside.