JDK dynamic proxy:
Generate an anonymous class that implements the proxy interface using interceptors (interceptors must implement InvocationHanlder) and reflection.
InvokeHandler is called before calling the specific method.
CGLiB dynamic proxy:
Using ASM open source package, the class file of the proxy object class is loaded in and processed by modifying its bytecode generation subclass.
When to use JDK or CGLiB?
The JDK’s dynamic proxy implementation of AOP is used by default if the target object implements an interface.
You can force CGLIB to implement AOP if the target object implements an interface.
3. If the target object does not implement an interface, the CGLIB library must be used, and Spring will automatically convert between JDK dynamic proxies and CGLIB.
How do I enforce AOP with CGLIB?
Jar, aspectJweaver -xxx.jar, cglib-nodep-xxx.jar
<aop:aspectj-autoproxy proxy-target-class=”true”/>
What is the difference between JDK dynamic proxy and CGLIB bytecode generation?
JDK dynamic proxies can only generate proxies for classes that implement interfaces, not for classes.
2. CGLIB implements proxying for classes, mainly by generating a subclass of the specified class, overriding the methods in it.
And override methods to implement enhancements, but because of inheritance, it is best not to declare the class or method final,
For final classes or methods, there is no inheritance. CGlib faster than JDK?
1. Use CGLib to realize dynamic proxy. CGLib uses ASM bytecode generation framework at the bottom and uses bytecode technology to generate proxy classes.
Reflection is more efficient than using Java before JDK6. The only thing to note is that CGLib cannot proxy methods that are declared final,
Because the principle of CGLib is to dynamically generate subclasses of proxied classes.
2. After JDK dynamic proxy optimization in JDK6, JDK7 and JDK8, JDK proxy efficiency is higher than CGLIB proxy efficiency in the case of fewer calls.
Jdk6 and JDk7 are only slightly less efficient than CGLIB proxies when making a lot of calls, but by jdK8 the JDK proxies are more efficient than CGLIB proxies,
In short, JDK agent efficiency has improved with each JDK version upgrade, and CGLIB agent messages have been a bit off the pace.
How does Spring choose to use JDK or CGLiB?
Spring uses the JDK’s dynamic proxy when the Bean implements the interface.
Spring uses CGlib as an implementation when the Bean does not implement the interface.
<aop:aspectj-autoproxy proxy-target-class=”true”/>