Implementation of Java Proxy is generally divided into static agents and dynamic agents (JDK agent and cglib agent)
Proxy mode
Simply say that the original business agent, the outside world through the proxy access to real objects, agents similar to the current intermediary agencies, real estate intermediary is an agent, Agent landlord, tenants as long as the agent to find agents without care about the landlord is who, agent can enhance the landlord's behavior on the basis of the landlord.
Proxy Mode Code
Java static proxy
Business interface
PackageCom.rrg.proxy.jdk.staticProxy;/** * * @authorABC **/ Public InterfaceCount {/*** Check Balance*/ Public voidQuerymoney (); /*** Transfer*/ Public voidTransferMoney ();}
Business Implementation Class
Package Com.rrg.proxy.jdk.staticProxy; Public class Implements Count { publicvoid Querymoney () { System.out.println("Querymoney ()" ); } Public void TransferMoney () { System.out.println("TransferMoney ()");} }
Agent
PackageCom.rrg.proxy.jdk.staticProxy;/*** java static proxy *@authorABC **/ Public classJdkstaticproxyImplementsCount {PrivateCountimpl Countimpl; Publicjdkstaticproxy (Countimpl countimpl) { This. Countimpl =Countimpl; } Public voidQuerymoney () {System.out.println ("= = = Start Query = = ="); Countimpl.querymoney (); System.out.println ("= = = Query End = = ="); } Public voidTransferMoney () {System.out.println ("= = = Start Transfer = = ="); Countimpl.transfermoney (); System.out.println ("= = = Transfer Success = = ="); }}
Test
/** * JDK static proxy */ @Test publicvoid test1 () { New Countimpl (); New Jdkstaticproxy (impl); Proxy.querymoney (); System.out.println (); Proxy.transfermoney (); }
Java Dynamic Agent
Analog Business Method Interface Userservice.java
Package com.rrg.proxy.jdk.dynamic;/** * Create a business interface * @author ABC * */public interface userservice { /** * New Person * /public void Add ();
Business method Implementation Userserviceimpl.java
Package Com.rrg.proxy.jdk.dynamic;public class Userserviceimpl implements userservice {public void Add () { System.out.println ("Add ()");} }
proxy class, responsible for handling agents
Packagecom.rrg.proxy.jdk.dynamic;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy; Public classJdkdynamichandlerImplementsInvocationhandler {PrivateUserService UserService; PublicJdkdynamichandler (UserService userservice) {Super(); This. UserService =UserService; } PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("= = = Add people processing = = ="); Object result=Method.invoke (UserService, args); System.out.println ("= = = Add people finished = = ="); returnresult; } PublicObject GetProxy () {//through the reflection mechanism, a proxy class object instance is created and returned. Used when a user makes a method call//When you create a proxy object, you need to pass the class loader for that business class (to get the metadata for the business implementation class, the wrapper method is to call the real business method), the interface, the handler implementation class returnProxy.newproxyinstance (Thread.CurrentThread (). Getcontextclassloader (), This. Userservice.getclass (). Getinterfaces (), This); }}
Test
/** * JDK Dynamic Agent * / @Test publicvoid test2 () { New Userserviceimpl (); New Jdkdynamichandler (userservice); = (UserService) handler.getproxy (); Proxy.add (); }
Cglib Dynamic Agent
No interface direct Proxy implementation class required
Business Implementation Class
Package Com.rrg.proxy.cglib; Public class Bookfacadeimpl { /** * Add book * /public void Addbook () { System.out.println("Addbook ()");} }
Agent
PackageCom.rrg.proxy.cglib;ImportJava.lang.reflect.Method;ImportNet.sf.cglib.proxy.Enhancer;ImportNet.sf.cglib.proxy.MethodInterceptor;ImportNet.sf.cglib.proxy.MethodProxy; Public classBookfacadecglibImplementsMethodinterceptor {PrivateBookfacadeimpl Bookservice; PublicObject getinstance (Bookfacadeimpl bookservice) {enhancer enhancer=NewEnhancer ();//Create a builder to create a dynamic proxy classEnhancer.setsuperclass ( This. Bookservice.getclass ());//Specifies the business class to be proxied for the reinforcement (that is, the parent class is specified for the proxy class generated below)//Set callback: callback is called for calls to all methods on the proxy class, and callback needs to implement the Intercept () method for blockingEnhancer.setcallback ( This); //creates a dynamic proxy class object and returns returnenhancer.create (); } //callback Method PublicObject Intercept (Object object, method, object[] args, Methodproxy methodproxy)throwsthrowable {System.out.println ("= = = Ready to add books = = ="); Methodproxy.invokesuper (object, args); System.out.println ("= = = Complete Add book = = ="); return NULL; }}
Test
/** * cglib Dynamic Agent * / @Test publicvoid test3 () { New Bookfacadeimpl (); New bookfacadecglib (); = (Bookfacadeimpl) cglib.getinstance (bookservice); Bookcglib.addbook (); }
Summarize
(1) Static proxy is to create a business proxy class at compile time, through proxy access to the same name method, implement the original method wrapper (proxy class inheritance business Class)
(2) The JDK dynamic agent invokes the business method of the same name in the dynamic proxy class through the method name of the interface, and implements the wrapper (Implementation Invocationhandler) of the original method.
(3) Cglib Dynamic Agent creates an enhanced business class (Implementation Methodinterceptor) by inheriting the business class
Agent is the embodiment of an AOP idea, which enhances the business method before and after the slicing programming
In spring's AOP programming:
If the target object that joins the container has an implementation interface, use the JDK proxy
If the target object does not implement an interface, use the Cglib proxy
Java Foundation (i)--proxy mode