Sub topic 14
Why calls inside the same class skip advice
This chapter assumes you know basic Spring dependency injection, how a Spring AOP proxy wraps a bean, and what @Transactional and @Around do at a surface level. It covers why self-invocation bypasses advice, how to confirm it, and the standard ways to fix it.
The symptom
A method carries @Transactional(propagation = Propagation.REQUIRES_NEW), and you expect each call to run in its own transaction. Yet nothing happens: no new transaction starts, and the logging or security aspect you wrote never fires. The method works when another bean calls it. It fails only when a method in the same class calls it.
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class ReportService {
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void saveReport(String name) {
// runs in its own transaction only when called through the proxy
}
public void saveAll(java.util.List<String> names) {
for (String name : names) {
saveReport(name); // self-invocation: calls 'this', not the proxy, so no advice applies
}
}
}When saveAll is called from a controller, the controller holds a reference to the proxy. The proxy has no advice for saveAll, so it delegates to the target. Inside the target, saveReport(name) is shorthand for this.saveReport(name). The name this refers to the raw target object, not the proxy. The call goes straight to the method body.
The mechanism
Spring AOP is proxy-based. The proxy is a separate object that sits in front of the target and runs advice before and after it delegates. Advice runs only when a call enters through the proxy.
With a JDK proxy, the proxy implements the interface and holds the target in a field. The target is an ordinary object that knows nothing about the proxy. With CGLIB, the proxy is a subclass that overrides methods. In current Spring versions it still delegates to a separate target instance, so the same rule holds.
The diagram below traces both paths.
What the language rules out
This is not a bug you can configure away. Java has no hook that lets a proxy intercept a call from an object to itself. The call this.saveReport() compiles to a direct invocation on the current object. Spring can only wrap the references it hands out to other beans.
Two consequences follow.
- Every proxy-based advice type is affected, not only transactions. Caching (
@Cacheable),@Async,@Retryable, security annotations and your own@Aroundaspects behave the same way. - Visibility does not matter. A public method called through
thisskips advice just like a private one.
Confirming the diagnosis
Before changing code, check that the call really bypasses the proxy. Two quick checks help.
- Log
AopUtils.isAopProxy(this)inside the method. It returnsfalsein the target, becausethisis the raw object. - Call the same method from another bean or a test. If advice runs there, the setup is correct and self-invocation is the cause.
import org.springframework.aop.support.AopUtils;
import org.springframework.stereotype.Service;
@Service
public class DiagnosticService {
public void outer() {
System.out.println("this is proxy: " + AopUtils.isAopProxy(this)); // false
inner();
}
public void inner() {
// advice for inner() does not run when reached from outer()
}
}Fixes, from cleanest to most invasive
Move the method to another bean
This is the recommended fix. Extract the advised method into a separate component and inject it. The call then crosses a bean boundary and goes through the proxy.
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
class ReportWriter {
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void saveReport(String name) {
// runs in its own transaction
}
}
@Service
public class ReportBatchService {
private final ReportWriter writer;
public ReportBatchService(ReportWriter writer) {
this.writer = writer;
}
public void saveAll(List<String> names) {
for (String name : names) {
writer.saveReport(name); // goes through the proxy
}
}
}This also tends to improve the design. The advised method usually represents a distinct unit of work, such as one transaction, and deserves its own name.
Inject the proxy into itself
A bean can receive a reference to its own proxy, typically with @Lazy to avoid a circular-dependency failure at startup. Calls through that field are advised.
import java.util.List;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class SelfInjectedReportService {
private final SelfInjectedReportService self;
public SelfInjectedReportService(@Lazy SelfInjectedReportService self) {
this.self = self;
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void saveReport(String name) {
// advised when called through 'self'
}
public void saveAll(List<String> names) {
for (String name : names) {
self.saveReport(name);
}
}
}It works, but the class now depends on itself. Readers have to know that self. and this. behave differently, and that difference is easy to erase in a later refactoring.
Expose the current proxy
With @EnableAspectJAutoProxy(exposeProxy = true), code can call AopContext.currentProxy() to get the proxy for the current invocation.
import org.springframework.aop.framework.AopContext;
((ReportService) AopContext.currentProxy()).saveReport(name);This couples business code to Spring AOP and throws an IllegalStateException if the proxy was not exposed. Use it only in legacy code that you cannot restructure.
Switch to AspectJ weaving
Compile-time or load-time weaving changes the bytecode of the class itself, so advice runs on internal calls too. This costs a build or JVM-agent setup, and the later chapter on AspectJ weaving covers when it is worth it.
Comparing the options
| Option | Advice on internal calls | Cost |
|---|---|---|
| Move to another bean | Yes | One extra class |
| Self-injection with `@Lazy` | Yes | Hidden self-dependency |
| `AopContext.currentProxy()` | Yes | Couples code to Spring AOP, needs `exposeProxy` |
| AspectJ weaving | Yes | Build or agent configuration |
Edge cases
- Transaction semantics hide the problem. With the default
REQUIREDpropagation, a self-invoked@Transactionalmethod still runs inside the caller's transaction, so the bug appears only when you rely onREQUIRES_NEW,NOT_SUPPORTED, a differentreadOnlyflag or a rollback rule. - Calls on a different instance still work. Calling
other.saveReport()whereotheris another bean of the same class goes through that bean's proxy. - Constructors and
@PostConstructrun before the proxy exists. Advice on methods called from there does not apply, for the same reason: the proxy is created after initialization finishes.
Exercise
A service has @Cacheable on findUser(long id) and a public method describe(long id) that calls findUser(id) directly. A controller calls describe twice with the same id, and the database is queried both times. Why does this happen, and what is the least invasive fix?
Show answer
describe runs on the target object, so its call to findUser is this.findUser(id) and does not pass through the caching proxy. The cache advice never runs. The least invasive fix is to move findUser into a separate bean and inject it into the service, so the call crosses the proxy.
Exercise
Why does AopUtils.isAopProxy(this) return false inside a proxied bean's method, and what does that tell you about self-invocation?
Show answer
Inside a method, this is the target object, not the proxy that wraps it. The result of false shows that any call made on this skips the proxy, so no advice can apply.