Video in progress
What is the difference between a JDK dynamic proxy and a CGLIB proxy, and when does Spring use which?
A JDK proxy is built from an interface and intercepts only the interface methods. CGLIB generates a subclass of the class. Since Boot 2.0 CGLIB is the default (proxyTargetClass=true), even when there is an interface.
📖 Answer
A JDK proxy is created with java.lang.reflect.Proxy and only works if there is an interface. The proxy's type is the interface, so if you inject the bean by its implementation class, you get:
Bean named 'orderService' is expected to be of type 'OrderServiceImpl'
but was actually of type 'jdk.proxy2.$Proxy87'
CGLIB creates a subclass at runtime and overrides the methods. That's why it can't proxy a final class or a final method: @Transactional on a final method silently does nothing. The constructor is not called twice (Objenesis handles that), but the class must not be final.
The reason Boot made CGLIB the default is simple: people kept injecting the implementation class and hitting the error above.
In Kotlin classes are final by default, so the kotlin-spring (all-open) plugin makes classes with Spring annotations open for you.
In practice, remember two things: don't write final methods in a bean that gets proxied, and a proxy only intercepts external calls.
Sign up to mark studied questions and save your progress.