Video in progress
When does Spring AOP create a proxy with a JDK dynamic proxy and when with CGLIB, and what does it affect in practice?
In Spring Boot 2+ the default is proxyTargetClass=true, meaning CGLIB: a subclass of the class is created. A JDK proxy works only through an interface. CGLIB can't wrap a final class or final methods, while a JDK proxy won't let you inject the bean by its concrete class type.
📖 Answer
Two mechanisms:
- JDK dynamic proxy:
java.lang.reflect.Proxybuilds a class at runtime that implements the bean's interfaces. The proxy is aPaymentServiceinterface, but not aPaymentServiceImpl. - CGLIB: generates bytecode to create a subclass like
PaymentServiceImpl$$SpringCGLIB$$0and overrides the methods.
By default, Spring Framework itself picks a JDK proxy when there's an interface. Spring Boot sets spring.aop.proxy-target-class=true as the default, so in Boot applications it's CGLIB almost everywhere.
Practical consequences:
- In JDK proxy mode, if you write
@Autowired PaymentServiceImpl impl, you get aBeanNotOfRequiredTypeExceptionat startup: the proxy is not that class. - With CGLIB, a
@Transactionalon afinalmethod is silently ignored: the subclass can't override it, so the call goes straight to the real code. In Kotlin, classes arefinalby default, so you need thekotlin-spring(all-open) plugin. - The fields inside a CGLIB proxy are empty: the proxy is a separate object and the state is in the real bean. If the proxy's fields show up as
nullin the debugger, this is why. - In Spring 4+, thanks to Objenesis, the constructor isn't called twice; that warning from old articles is no longer relevant.
To check: AopUtils.isCglibProxy(bean), AopUtils.isJdkDynamicProxy(bean), or just log bean.getClass().
Sign up to mark studied questions and save your progress.