Dynamic Agent (JDK dynamic proxy, CGLib)

A. JDK dynamic proxy specific implementation principle

  • Interface to create your own call processor by implementing InvocationHandlet;

  • To create a dynamic proxy ClassLoader by specifying a set of interface objects and for the Proxy class;

  • Obtaining dynamic proxy class constructor by reflection, which is the only parameter type call processor interface type;

  • By creating dynamic proxy class instance constructor object configured to call the handler as a parameter into the parameter;

    JDK dynamic proxy is a proxy for the interface mode, if the proxy is not the interface that the target can not do anything Spring, Spring production of new anonymous proxy class that implements the interface through the Java reflection mechanism, which rewrote the enhancement of AOP.

Two. CGLib dynamic proxies

CGLib is a powerful, high-performance production Code libraries, can achieve dynamic expansion java runtime class, Spring succession during the run to be a dynamic proxy class by CGlib, the parent class rewritten to achieve AOP Aspect Oriented Programming with it.

III. Comparison between the two

  • JDK dynamic proxy is an interface-oriented.
    CGLib dynamic proxy is achieved (if the proxy class is modified by the final keyword, so sorry fail) to be inherited by the bytecode underlying proxy class.

  • Performance:
    About performance between the two words, JDK dynamic proxy proxy object created in previous versions of the JDK, the performance is not very high, although JDK dynamic proxy objects in high-performance version has been greatly improved but he also does not apply to all scenarios.

    Mainly in the following two indicators:

    CGLib dynamic proxy object created in the actual run time performance than high JDK dynamic proxy lot of studies have shown that probably 10 times higher;

    But when the time CGLib create objects than it takes to JDK dynamic proxy lot more, studies have shown that about 8 times the gap;

    Thus, for a proxy object or a proxy instance of singleton pool, because without frequent create a proxy object, it is more suitable for CGLib dynamic proxy, anyway, is more suitable for JDK dynamic proxy.

Published 70 original articles · won praise 4 · Views 6341

Guess you like

Origin blog.csdn.net/qq_44837912/article/details/104748732