Video in progress

Strong Middle 🧭 Design patterns

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.Proxy builds a class at runtime that implements the bean's interfaces. The proxy is a PaymentService interface, but not a PaymentServiceImpl.
  • CGLIB: generates bytecode to create a subclass like PaymentServiceImpl$$SpringCGLIB$$0 and 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:

  1. In JDK proxy mode, if you write @Autowired PaymentServiceImpl impl, you get a BeanNotOfRequiredTypeException at startup: the proxy is not that class.
  2. With CGLIB, a @Transactional on a final method is silently ignored: the subclass can't override it, so the call goes straight to the real code. In Kotlin, classes are final by default, so you need the kotlin-spring (all-open) plugin.
  3. 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 null in the debugger, this is why.
  4. 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().