1. Static Proxy
Subject object: Student
Public Interface Student { public String Add ();}
Target object: realstudent
Public class Realstudent implements Student { public String Add () { System. out. println ("add OK"); return NULL ; }}
Proxy object: Proxstudent
Public classProxstudent implements Student {//Interaction between Objects PrivateStudent realstudent; PublicStudent getrealstudent () {returnrealstudent; } Public voidsetrealstudent (Student realstudent) { This. realstudent =realstudent; This. realstudent=realstudent; } PublicString Add () {System. out. println ("The transaction is open! "); returnRealstudent.add (); }}
Single Test
// Static proxy @Test publicvoid test01 () { // Real Theme Object Student student=New realstudent (); // proxy Object Proxstudent proxstudent=New proxstudent (); Proxstudent.setrealstudent (student); Proxstudent.add (); }
2.JDK Dynamic Agent
Interface: Iuserdao
Public Interface Iuserdao { public String Add (); Public String edit ();}
Class: Userdaoimpl
Public classUserdaoimpl implements Iuserdao { PublicString Add () {System. out. println ("Add"); return "Add"; } PublicString edit () {System. out. println ("Edit"); return "Edit"; }}
Single Test
//JDK Dynamic Agent@Test Public voidtest02 () {final Iuserdao dao=NewUserdaoimpl (); Iuserdao Proxy= (Iuserdao) proxy.newproxyinstance (Dao.getclass (). getClassLoader (), Dao.getclass (). Getinterfaces (),NewInvocationhandler () { Publicobject Invoke (Object proxy, Method method, object[] args) throws Throwable {System. out. println ("The transaction is open ."); Method.invoke (Dao,args); return NULL; } }); //proxy Object Add () edit ()Proxy.add (); Proxy.edit (); }
3.CGLIB Dynamic Agent
Public class UserService { publicvoid dalete () { System. out. println ("dalete OK");} }
Single test mode one
//CGLIB Dynamic Agent one@Test Public voidtest03 () {Final UserService service=NewUserService (); Enhancer Enhancer=Newenhancer (); //building subclasses of business classes in memoryEnhancer.setsuperclass (Service.getclass ()); Enhancer.setcallback (NewOrg.springframework.cglib.proxy.InvocationHandler () { Publicobject Invoke (Object O, Method method, object[] objects) throws Throwable {System. out. println ("The transaction is open ."); Method.invoke (service,objects); return NULL; } }); UserService Proxy=(UserService) enhancer.create (); Proxy.dalete (); }
Single test mode two
//CGLIB Dynamic Agent two@Test Public voidtest04 () {Final UserService service=NewUserService (); Enhancer Enhancer=Newenhancer (); //building subclasses of business classes in memoryEnhancer.setsuperclass (Service.getclass ()); Enhancer.setcallback (NewMethodinterceptor () { PublicObject Intercept (Object o, Method, object[] objects, Methodproxy methodproxy) throws Throwable { System. out. println ("The transaction is open ."); Methodproxy.invoke (service,objects); return NULL; } }); UserService Proxy=(UserService) enhancer.create (); Proxy.dalete (); }
Spring Proxy mode