Sub topic 5
CGLIB Proxies and Subclassing
This chapter assumes you know core Java (interfaces, inheritance, annotations), basic Spring dependency injection, and the JDK dynamic proxy from the previous chapter. It explains how Spring builds a proxy for a class that has no interface, and which Java rules that approach depends on.
The problem JDK proxies cannot solve
A JDK dynamic proxy implements the interfaces you give it. It cannot proxy a class that implements no interface, and it cannot be cast to the concrete class. If a bean is just class InvoiceService with no interface, Proxy.newProxyInstance has nothing to implement.
CGLIB solves this by generating a subclass of the target class at runtime. The subclass overrides each overridable method. Each override runs the advice and then calls the original method on a separate target object.
Spring repackages CGLIB inside spring-core (org.springframework.cglib), so you add no dependency. Since Spring 4, the target class does not need a default constructor. Spring creates the proxy instance with Objenesis, which skips the constructor.
How the generated subclass behaves
Suppose you have this bean:
import org.springframework.stereotype.Service;
@Service
public class InvoiceService {
public String create(String customer) {
return "invoice for " + customer;
}
}Conceptually, Spring generates a class like the one below. This is a simplified sketch, not the real generated code:
public class InvoiceService$$SpringCGLIB$$0 extends InvoiceService {
private final InvoiceService target; // the real bean
private final java.util.List<Runnable> advice = new java.util.ArrayList<>();
InvoiceService$$SpringCGLIB$$0(InvoiceService target) {
this.target = target;
}
@Override
public String create(String customer) {
// run interceptors (advice), then:
return target.create(customer);
}
}The proxy is-a InvoiceService, so you can inject it anywhere that type is expected. The real bean is a separate object that the proxy holds. This matters for fields. The proxy's own fields are never initialized by your constructor logic, so reading a field directly on a proxy gives you null or 0, not the target's value. Always go through methods.
The diagram below shows the structure.
JDK proxy versus CGLIB proxy
| Aspect | JDK dynamic proxy | CGLIB proxy |
|---|---|---|
| Mechanism | Implements interfaces | Subclasses the target class |
| Needs an interface | Yes | No |
| Injectable as concrete class | No | Yes |
| `final` class | Not affected | Cannot be proxied |
| `final` method | Not affected (interface methods) | Not intercepted |
| Package-private and `protected` methods | Not applicable | Intercepted only if the proxy is in the same class loader and package |
Which proxy Spring picks
Spring uses a JDK proxy when the target implements at least one interface, and CGLIB otherwise. Spring Boot changes this default. It sets spring.aop.proxy-target-class=true, so Boot applications use CGLIB even for beans that implement interfaces.
You can force the choice yourself:
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
class AopConfig {
}The difference shows up when you inject by type. Consider a bean that implements GreetingService. With a JDK proxy, a field of type GreetingServiceImpl fails with a BeanNotOfRequiredTypeException, because the proxy is not an instance of that class. With CGLIB it works.
Rules that follow from subclassing
Subclassing brings the usual Java inheritance limits.
finalclasses cannot be proxied. Spring fails at startup with anAopConfigExceptionor anIllegalArgumentExceptionabout a final class.finalmethods are not intercepted. A subclass cannot override them. The call runs on the proxy instance itself, not on the target. Because the proxy's fields are empty, afinalmethod can read uninitialized state and misbehave.privatemethods are not intercepted. They are not overridden.staticmethods are not intercepted. They belong to the class, not an instance.- Constructors run twice in older setups. Before Objenesis, the constructor ran for both the target and the proxy. Modern Spring avoids this, but side effects in constructors remain a poor idea.
Kotlin users hit rule 1 and 2 often, because Kotlin classes are final by default. The kotlin-spring compiler plugin opens classes annotated with Spring stereotypes.
Seeing the proxy type
You can check which proxy you received without a debugger:
import org.springframework.aop.support.AopUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
class ProxyInspector implements CommandLineRunner {
private final InvoiceService service;
ProxyInspector(InvoiceService service) {
this.service = service;
}
@Override
public void run(String... args) {
System.out.println("class = " + service.getClass().getName());
System.out.println("isAopProxy = " + AopUtils.isAopProxy(service));
System.out.println("isCglib = " + AopUtils.isCglibProxy(service));
System.out.println("isJdk = " + AopUtils.isJdkDynamicProxy(service));
System.out.println("target = " + AopUtils.getTargetClass(service).getName());
}
}With a CGLIB proxy, the printed class name contains $$SpringCGLIB$$ (older versions print $$EnhancerBySpringCGLIB$$). A JDK proxy prints a name like jdk.proxy2.$Proxy45.
Edge cases
- Proxy identity.
service == targetis false. Code that compares references or puts beans in an identity map can behave unexpectedly. - Equals and hashCode. Spring routes these through the proxy, so they usually behave, but a
final equalswould not be intercepted. - Class loading. CGLIB defines the generated class in the target's class loader. On Java 17 and later, Spring uses
MethodHandles.Lookupfor this, so no--add-opensflag is needed in current versions. - Startup cost. Generating classes adds a little startup time. Native image builds generate proxies at build time, so every proxy type must be known in advance.
- Package-private methods. These can be intercepted only when the generated class lands in the same package and class loader as the target. Do not rely on this.
Exercise
A bean PriceCalculator has no interface, and one of its methods is declared public final BigDecimal discount(). An aspect with @Around("execution(* PriceCalculator.*(..))") is active. Is advice applied to discount(), and what else can go wrong?
Show answer
No. CGLIB proxies by subclassing, and a subclass cannot override a final method, so discount() runs directly on the proxy instance and skips the advice. Because the proxy was created without running your constructor logic, fields on the proxy are uninitialized, so discount() may read null or 0 instead of the target's state. Fix it by removing final from the method.
Exercise
A bean implements GreetingService. You inject it into a field of type GreetingServiceImpl and get a BeanNotOfRequiredTypeException. Give two ways to fix it.
Show answer
Inject the interface type GreetingService, which works for any proxy type. Alternatively, force CGLIB with @EnableAspectJAutoProxy(proxyTargetClass = true) (or spring.aop.proxy-target-class=true), so the proxy is a subclass of GreetingServiceImpl.