Sub topic 17
Inspecting and Debugging Proxies
This chapter assumes you know core Java, Spring dependency injection, and the proxy basics from earlier chapters: JDK dynamic proxies, CGLIB subclassing, and how Spring wraps beans. Here you will learn to answer three questions when advice misbehaves. Is this object a proxy? What kind of proxy is it? Why did a call skip the advice?
Why you need to look at proxies
Most AOP bugs have one cause: the call did not go through the proxy, or the proxy was not created. The stack trace and the injected object tell you which. If you can read them, you can diagnose most problems in a few minutes.
Symptoms you will meet:
- Advice never runs for a bean you expected to be advised.
- A
@Transactionalmethod does not roll back. - A
ClassCastExceptionwhen you cast an injected bean to its implementation class. - A
NullPointerExceptionon a field of a CGLIB-proxied bean. - Stack traces full of
$Proxyand$$SpringCGLIB$$frames.
Recognizing a proxy by its class name
The runtime class of a proxy gives the first clue.
| Proxy type | Typical class name | Extends or implements |
|---|---|---|
| JDK dynamic proxy | `jdk.proxy2.$Proxy57` (older JDKs: `com.sun.proxy.$Proxy57`) | Implements the target's interfaces, does not extend the target class |
| CGLIB proxy | `com.example.ReportService$$SpringCGLIB$$0` (older Spring: `$$EnhancerBySpringCGLIB$$...`) | Subclasses the target class |
The exact numbers and package names vary by JDK and Spring version. The markers $Proxy and CGLIB are what to look for.
Using Spring's AopUtils and AopProxyUtils
Do not compare class names in code. Spring provides utilities for that.
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class ProxyInspector {
@Bean
CommandLineRunner inspect(ReportService service) {
return args -> {
System.out.println("class = " + service.getClass().getName());
System.out.println("isAopProxy = " + AopUtils.isAopProxy(service));
System.out.println("isJdkProxy = " + AopUtils.isJdkDynamicProxy(service));
System.out.println("isCglibProxy = " + AopUtils.isCglibProxy(service));
System.out.println("targetClass = " + AopUtils.getTargetClass(service).getName());
System.out.println("ultimate = "
+ AopProxyUtils.ultimateTargetClass(service).getName());
};
}
}What each call returns:
AopUtils.isAopProxy(obj)is true for a JDK or CGLIB proxy created by Spring AOP.AopUtils.isJdkDynamicProxy(obj)andAopUtils.isCglibProxy(obj)tell you which kind.AopUtils.getTargetClass(obj)returns the class behind the proxy. For a CGLIB proxy it is the superclass. For a JDK proxy it asks the proxy'sTargetClassAwaresupport.AopProxyUtils.ultimateTargetClass(obj)unwraps nested proxies until it reaches the real class.
If isAopProxy is false for a bean you expected to be advised, no advisor matched it, or the bean was not created through the container. Check the pointcut and the bean's package before anything else.
Reaching the target and the advisors
When a bean is proxied by Spring AOP, the proxy implements Advised. Through it you can list the advisors and fetch the target.
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.support.AopUtils;
public class AdvisedPrinter {
public static void print(Object bean) throws Exception {
if (!AopUtils.isAopProxy(bean)) {
System.out.println(bean.getClass().getName() + " is not a proxy");
return;
}
Advised advised = (Advised) bean;
System.out.println("proxyTargetClass = " + advised.isProxyTargetClass());
System.out.println("target = " + advised.getTargetSource().getTarget());
for (Advisor advisor : advised.getAdvisors()) {
System.out.println("advisor = " + advisor);
}
}
}The advisor list shows which aspects Spring attached and in what order. It helps when two aspects run in an unexpected sequence, because the list shows the order Spring actually built. isProxyTargetClass() reports whether the proxy uses CGLIB class-based proxying.
Reading a proxy stack trace
When advice calls the target, the stack contains framework frames between your caller and your method. Here is a trimmed trace from an exception in ReportService.saveReport, reading from the top (innermost) down:
at com.example.ReportService.saveReport(ReportService.java:14)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(...)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:...)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(...)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(...)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(...)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(...)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(...)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(...)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(...)
at com.example.ReportService$$SpringCGLIB$$0.saveReport(<generated>)
at com.example.ReportController.create(ReportController.java:22)Read it from the bottom: the controller calls the generated CGLIB subclass, which hands the call to DynamicAdvisedInterceptor. The interceptor chain runs, with ReflectiveMethodInvocation.proceed appearing once per link. The transaction interceptor is one of them. Finally the real method runs. A JDK proxy shows JdkDynamicAopProxy.invoke and a $Proxy frame in the same place.
Practical use of this:
- No proxy frame between caller and target means the call bypassed the proxy. This is the signature of self-invocation.
- A missing interceptor frame means that advice was not applied to this method.
- Many repeated
proceedframes are normal. They are not recursion.
Turning on AOP logging
Spring logs proxy creation and advice selection at DEBUG. In application.properties:
logging.level.org.springframework.aop=DEBUG
logging.level.org.springframework.transaction.interceptor=TRACEThe transaction level at TRACE prints lines such as "Getting transaction for [com.example.ReportService.saveReport]". If that line is missing when you call the method, the call never reached the interceptor.
A checklist for "my advice does not run"
Work through these in order. Each step rules out one cause.
- Is the object a proxy? Use
AopUtils.isAopProxy. If not, go to step 2. If yes, go to step 4. - Is the bean managed by Spring? Objects created with
neware never proxied. - Is AOP enabled, and does the aspect have
@Component(or a@Beandefinition) as well as@Aspect?@Aspectalone does not register a bean. - Does the pointcut match? Check the package, the method visibility and the annotation retention. A custom annotation needs
RetentionPolicy.RUNTIME. - Did the call pass through the proxy? Look for the proxy frame in a stack trace. Self-invocation fails here.
- Is the method
final,private, orstatic? A CGLIB proxy cannot override these, so advice is skipped silently.
Casting errors
Injecting by implementation class fails when the bean is a JDK proxy:
@Autowired
private GreetingServiceImpl service; // fails if the bean is a JDK proxyA JDK proxy implements GreetingService but is not a GreetingServiceImpl, so Spring cannot inject it. Inject the interface instead. Alternatively, set spring.aop.proxy-target-class=true to force CGLIB. Spring Boot already defaults to true, so this error is most common in plain Spring setups, where the default is interface-based proxies.
Exercise
A @Service class named InvoiceService has an advised public method send() and a final method audit(). Both are called from a controller. send() is timed by your aspect, but audit() is not, and it throws a NullPointerException on an injected field. What is happening, and how do you confirm it?
Show answer
The bean is a CGLIB proxy. CGLIB subclasses cannot override final methods, so audit() runs directly on the proxy instance. The proxy's own fields were never populated by dependency injection, so the field is null. Confirm it with AopUtils.isCglibProxy(service) returning true and a stack trace for audit() that has no DynamicAdvisedInterceptor frame. Fix it by removing final from audit() (or making the class non-final in a Kotlin project that uses the allopen plugin).
Exercise
You inject a bean into a test and AopUtils.isAopProxy(bean) returns true. How do you list the aspects that apply to it, and which call returns the unwrapped object?
Show answer
Cast the bean to Advised and call getAdvisors() to list the advisors. Call getTargetSource().getTarget() on the Advised (or AopTestUtils.getTargetObject(bean) in tests) to get the real object.