The most detailed proxy explanation-JDK dynamic proxy and cglib proxy

Source: Internet
Author: User

1. Agent-related concepts

Proxy Mode

Proxy mode is called proxy or surrogate in English, which can be translated as "proxy". A proxy means that one person or one institution takes action on behalf of another person or another institution. In some cases, a client does not want or cannot directly reference an object, and the proxy object can play a mediation role between the client and the target object.

Abstract topic role

Declares the common interface between the real subject and the proxy topic, so that the proxy topic can be used wherever the real topic can be used.

Proxy) Role

The proxy topic role contains a reference to a real topic, so that you can operate on real theme objects at any time. The proxy topic role provides the same interface as the real topic role, in this way, you can replace real themes to control the reference to real themes at any time, and create real theme objects (and delete real theme objects) as needed ); A proxy role usually performs an operation before or after passing a client call to a real topic, rather than simply passing the call to a real topic object.

Real topic role

Defines the real object represented by the proxy role

Spring has two proxy methods:

1. If the target object implements several interfaces, spring uses JDK's Java. Lang. Reflect. proxy class proxy.

2. If the target object does not implement any interfaces, spring uses the cglib library to generate a subclass of the target object.

2. Case Analysis: Similarities and differences between the two proxies

JDK dynamic proxy

Note:Compile the JDK proxy class to reference the proxy under the reflection package in the Java toolkit Lang. You do not need to introduce other jar packages, but be sure not to flip the wrong package. Import Java. lang. reflect. proxy; the target object implements several interfaces.

Two interface classes: saybyebye and saygoodbye

Package www. csdn. spring. proxy. JDK; public interface saybyebye {public void saybyebye ();} package www. csdn. spring. proxy. JDK; public interface saygoodbye {public void saygoodbye (string content);} saybyeimplementpackage www. csdn. spring. proxy. JDK; public class saybyeimpl implements saygoodbye, saybyebye {@ overridepublic void saygoodbye (string content) {system. out. println ("say:" + content) ;}@ override Public void saybyebye () {system. Out. println ("say: Bye bye! ") ;}} JDK proxy class jdkproxypackage www. csdn. spring. proxy. JDK; import Java. lang. reflect. invocationhandler; import Java. lang. reflect. method; import Java. lang. reflect. proxy; public class jdkproxy implements invocationhandler {// proxy target object private object target; // create the proxy object public object createproxyinstance (object target) of the target object {// proxy target this.tar get = target; // create a proxy object // 1. Define the class loader of the proxy class // 2. List of interfaces to be implemented by the proxy class // 3. Assign the method call handler retu Rn proxy. newproxyinstance (target. getclass (). getclassloader (), target. getclass (). getinterfaces (), this);}/*** Proxy: proxy instance of the target object. Change the proxy instance to class $ proxy4 no matter how many times it is run; * method: * ARGs: method parameter */@ overridepublic object invoke (Object proxy, method, object [] ARGs) throws throwable {/** test the meaning of the three parameters of the invoke Method */system. out. println ("Proxy:" + proxy. getclass (); system. out. println ("method:" + method. Getname (); If (ARGs! = NULL & args. length> 0) {for (Object OBJ: ARGs) {system. out. println ("ARGs:" + OBJ) ;}// declare the returned object returnvalue = NULL; beforemethod (); returnvalue = method. invoke (target, argS); aftermethod (); Return returnvalue;} public void beforemethod () {system. out. println ("---- operation before method execution ----");} public void aftermethod () {system. out. println ("---- action after method execution ----") ;}} test class protestpackage www. csdn. spring. proxy. JDK; import Org. JUnit. Test; public class proxytest {@ testpublic void testsay () {// saybyeimpl = new saybyeimpl ();/** // when proxy is not used * saybyeimpl. saygoodbye ("I want to divorce! "); * Saybyeimpl. saybyebye (); * // proxy topic role. The same interface class implemented by the proxy topic and the real topic is used to receive the created proxy topic, is to create a target class saygoodbye = (saygoodbye) New jdkproxy (). createproxyinstance (saybyeimpl); saybyebye = (saybyebye) New jdkproxy (). createproxyinstance (saybyeimpl); saygoodbye. saygoodbye ("No, I want to divorce! "); System. Out. println (" 00000000000000000000000000000000000000000000000 "); saybyebye. saybyebye ();}}

Cglib as proxy

 Cglib is a powerful, high-performance, high-quality code generation class library. It can expand Java classes and implement Java interfaces at runtime.

Note:Using cglib as a proxy, Java does not want JDK dynamic proxy that encapsulate the corresponding class, he needs to import the dependent jar package asm-3.3.jar, cglib-2.2.jar these two jar packages; the target object does not implement any interfaces.

Target class sayhello

PackageWww. csdn. Spring. Proxy. cglib;

 

PublicclassSayhello {

PublicvoidSay (string content ){

System.Out. Println ("say:" + content );

}

}

Cglib proxy cglibproxy

Package www. csdn. spring. proxy. cglib; import Java. lang. reflect. method; import net. SF. cglib. proxy. enhancer; import net. SF. cglib. proxy. methodinterceptor; import net. SF. cglib. proxy. methodproxy; public class cglibproxy implements methodinterceptor {private object target; public object createproxyinstance (Object target?#this.tar get = target; // generate the proxy object enhancer = new enhancer (); // set the parent class enhancer of the proxy object. setsu Perclass(this.tar get. getclass (); // sets the callback enhancer. setcallback (this); // create the proxy object return enhancer. create ();}/*** Proxy: the instance of the target object proxy; * method: The Method Instance for the target object to call the parent method; * ARGs: call the parent method to pass the parameter * methodproxy: the proxy method to call the target Method */@ overridepublic object intercept (Object proxy, method, object [] ARGs, methodproxy) throws throwable {/** test the meaning of the four parameters of the invoke Method */system. out. println ("Proxy:" + proxy. getclass (); system. Out. println ("method:" + method. getname (); system. Out. println ("methodproxy:" + methodproxy. getsupername (); If (ARGs! = NULL & args. length> 0) {for (Object OBJ: ARGs) {system. out. println ("ARGs:" + OBJ) ;}// declare the returned object returnvalue = NULL; beforemethod (); // you can call the invoke method using both the method and methodproxy parameters, and the execution results are the same. // returnvalue = methodproxy. invoke (target, argS); returnvalue = method. invoke (target, argS); aftermethod (); Return returnvalue;} public void beforemethod () {system. out. println ("---- operation before method execution ----");} public void aftermethod () {System. Out. println ("---- operation after method execution ----") ;}} test class proxytestpackage www. csdn. spring. proxy. cglib; import Org. JUnit. test; public class proxytest {@ testpublic void testsay () {// sayhello = new sayhello (); // sayhello. say ("Hi! Hello! "); // Creates an object of the target class. The JDK dynamic proxy creates an Interface Class Object. cglib does not implement any interfaces, therefore, you can directly create a target Class Object sayhello SH = (sayhello) New cglibproxy (). createproxyinstance (sayhello); SH. say ("Hi! Hello! ");}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.