Java dynamic Proxy and method interception (Implementation of AOP using Cglib)

Source: Internet
Author: User

Classic AOP is generally simpler and more controllable with Cglib through the spring framework.

The implementation of dynamic proxies is very elegant.

Entity class:

 Public class SampleClass {    public  string MyFunction1 (String input) {        System.out.println (" The MyFunction1 method is called: Hello: "+ input"        ; return "Hello:" + input;    }      Public string MyFunction2 (String input) {        System.out.println ("MyFunction2 method called: Hello:" + input);         return "Hello:" + input;    }}

ImportNet.sf.cglib.proxy.Callback;ImportNet.sf.cglib.proxy.Dispatcher;ImportNet.sf.cglib.proxy.Enhancer;ImportNet.sf.cglib.proxy.FixedValue;ImportNet.sf.cglib.proxy.LazyLoader;Importnet.sf.cglib.proxy.NoOp;ImportNet.sf.cglib.proxy.ProxyRefDispatcher; Public classCglibtest {Private StaticString MyName = "";  Public Static voidMain (string[] args) {MyName= "Wang Xin";        DOAOP (); Enhancer Enhancer1=Enhancernoop (); SampleClass Proxy=(SampleClass) enhancer1.create (); String Stroutput= Proxy. MyFunction2 ("Zhao Qi"); System.out.println ("Enhancernoop:" +stroutput); Enhancer Enhancer2=Enhancerfixedvalue (); SampleClass Proxy2=(SampleClass) enhancer2.create (); String StrOutput2= Proxy2. MyFunction2 ("Zhao Qi"); System.out.println ("Enhancerfixedvalue:" +strOutput2); }    Private Static voidDoaop () {myinterceptor cglib=NewMyinterceptor (); SampleClass Bookcglib=(SampleClass) cglib. getinstance (NewSampleClass ()); Bookcglib.myfunction2 ("Zhang San"); }    //This callback replaces the method implementation of the original class    Private StaticEnhancer Enhancerfixedvalue () {Enhancer enhancer=Newenhancer (); Enhancer.setsuperclass (SampleClass.class); Enhancer.setcallback (NewFixedvalue () {@Override PublicObject Loadobject ()throwsException {//returns MyName as the input parameter;                return NewSampleClass ().            MyFunction2 (MyName);        }        }); returnenhancer; }        //Execute the original (Super) class method    Private StaticEnhancer Enhancernoop () {Enhancer enhancer=Newenhancer (); Enhancer.setsuperclass (SampleClass.class);        Enhancer.setcallback (noop.instance); returnenhancer; }        //Lazy Loading    Private StaticEnhancer Enhancerlazyloader () {Enhancer enhancer=Newenhancer (); Enhancer.setsuperclass (SampleClass.class); Enhancer.setcallback (NewLazyloader () {@Override PublicObject Loadobject ()throwsException {//return "returned value after callback";                return NewSampleClass ().            MyFunction2 (MyName);        }        }); returnenhancer; }        Private StaticEnhancer Enhancerproxyrefdispatcher (FinalString obj1) {Enhancer enhancer=Newenhancer (); Enhancer.setsuperclass (SampleClass.class); Enhancer.setcallback (NewProxyrefdispatcher () {@Override PublicObject Loadobject (Object obj2)throwsException {return NewSampleClass (). MyFunction2 (Obj1 +(String) obj2);        }        }); returnenhancer; }}

AOP Interception Simulation Class:

ImportNet.sf.cglib.proxy.Enhancer;ImportNet.sf.cglib.proxy.MethodInterceptor;ImportNet.sf.cglib.proxy.MethodProxy; Public classMyinterceptorImplementsMethodinterceptor {PrivateObject Target;  Publicobject GetInstance (object target) { This. target =Target; Enhancer Enhancer=Newenhancer (); Enhancer.setsuperclass ( This. Target.getclass ()); //callback MethodEnhancer.setcallback ( This); //Create a proxy object        returnenhancer.create (); } @Override//callback Method     PublicObject Intercept (Object obj, Java.lang.reflect.Method Method, object[] args, methodproxy proxy)throwsthrowable {System.out.println ("Do something before you intercept.");          Proxy.invokesuper (obj, args); System.out.println ("After the interception, do something else."); return NULL; }    }  

Output:

Do something before you intercept.
The MyFunction2 method is called: Hello: Zhang San
After the Intercept, do something else.
The MyFunction2 method is called: Hello: Zhao Qi
Enhancernoop:hello: Zhao Qi
The MyFunction2 method is called: Hello: Wang Xin
Enhancerfixedvalue:hello: Wang Xin

methoddelegate

Method Delegate: Implements a delegate similar to C #. To bind a method call to a specific method of an interface

     Public voidTestmethoddelegate ()throwsException {Samplebean bean=NewSamplebean (); Bean.setvalue ("Hello cglib!"); Beandelegate Delegate=(beandelegate) methoddelegate.create (Bean,"GetValue", beandelegate.class); Assertequals ("Hello world!", Delegate.getvaluefromdelegate2 ()); }     Public InterfaceBeandelegate {//String getValueFromDelegate1 ();String GetValueFromDelegate2 (); }

Bulkbean

Accessor method calls using an array to access the bean

     Public voidTestbulkbean ()throwsException {Bulkbean Bulkbean= Bulkbean.create (Samplebean.class,                NewString[] {"GetValue"},NewString[] {"SetValue" },                NewClass[] {String.class }); Samplebean Bean=NewSamplebean (); Bean.setvalue ("Hello world!"); Assertequals (1, Bulkbean.getpropertyvalues (bean). length); Assertequals ("Hello world!", bulkbean.getpropertyvalues (Bean) [0]); Bulkbean.setpropertyvalues (Bean,NewObject[] {"Hello cglib!" }); Assertequals ("Hello cglib!", Bean.getvalue ()); }
 Public class Samplebean {  private  String value;    Public String GetValue () {    return  value;  }    Public void SetValue (String value) {    this. Value = value;  }} 

Java dynamic Proxy and method interception (Implementation of AOP using Cglib)

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.