Spring proxies: JDK dynamic vs CGLIB
You put @Transactional on a method and a database transaction opens before it runs and commits when it returns — yet you never wrote a line to start or end one. You add @Cacheable , and the second call with the same arguments skips your method body entirely. You didn't touch the code inside those methods. So where does the extra behaviour actually run? It runs inside a proxy : a stand-in object…
In the world of Java, a proxy is an object that stands between a caller and a real object, adding extra functionality without changing the original code. Spring, a popular Java framework, uses proxies to implement cross-cutting concerns like transactions, caching, security, retries, and async processing. These concerns can be added to methods using annotations, and the framework handles the rest.
There are two ways Spring creates these proxies at runtime: JDK dynamic proxy and CGLIB proxy. Both approaches aim to add the same functionality, but they differ in the mechanism used to generate the proxy.
The JDK dynamic proxy, introduced in Java 1.3, allows generating an object at runtime with a set of interfaces. A custom handler is written that gets called for every method on the proxy. The handler can perform additional work before and after invoking the target object's method. This approach, however, only works when the bean has an interface to mirror.
On the other hand, CGLIB (Code Generation Library) comes into play when the bean has no interface. CGLIB generates a subclass of the real class at runtime and overrides its methods. The proxy is a genuine instance of the real class, and the original methods are overridden to add the extra functionality. This mechanism allows Spring to create proxies for beans without interfaces.
In summary, Spring uses either the JDK dynamic proxy or CGLIB proxy to generate stand-ins for beans, enabling cross-cutting concerns to be added seamlessly without modifying the original code. The choice between the two depends on whether the bean has an interface or not.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.