The agent is a common design pattern in Java, the proxy class is called by the related methods of the proxy class, and the related methods are enhanced. Add some non-business code, such as transaction, log, alarm send mail and so on.
Second, the JDK static proxy
1. Business interface
/** * Business Interface * @author PC * */public interface UserService {//Add a user public void AddUser ();//Edit Account public void Edituser ();}
2. Business Realization Class
/** * Business Implementation class * @author PC * */public class Userserviceimpl implements UserService {public void AddUser () {System.out.printl N ("Add a user ... ");} public void Edituser () {System.out.println ("Edit a user ... ");}}
3. Agent Class
/** * Proxy class * * @author pc * */public class Userserviceproxy implements UserService {private Userserviceimpl Userimp L;public userserviceproxy (Userserviceimpl countimpl) {This.userimpl = Countimpl;} public void AddUser () {System.out.println ("proxy class method, enhanced ... "); System.out.println ("Transaction begins ... ");//method of invoking the delegate class; Userimpl.adduser (); SYSTEM.OUT.PRINTLN ("Processing end ... ");} public void Edituser () {System.out.println ("proxy class method, enhanced ... "); System.out.println ("Transaction begins ... ");//method of invoking the delegate class; Userimpl.edituser (); System.out.println ("End of transaction ... ");}}
4. Test class
public static void Main (string[] args) {Userserviceimpl Userimpl = new Userserviceimpl (); Userserviceproxy proxy = new Userserviceproxy (Userimpl);p roxy.adduser (); System.out.println ("----------Split Line----------");p Roxy.edituser ();}
5. Results
Proxy class method, has been enhanced ... Transaction start ... Add a user ... Processing end ... ----------Split Line----------proxy class method, has been enhanced ... Transaction start ... Edit a user ... End of transaction ...
Third, the JDK dynamic agent
1. Business interface
/** * Business Interface * @author PC * */public interface UserService {//Add a user public void AddUser ();//Edit Account public void Edituser ();}
2. Business interface Implementation Class
/** * Business Interface Implementation class * @author PC * */public class Userserviceimpl implements UserService {public void AddUser () {System.out.prin TLN ("Add a user ... ");} public void Edituser () {System.out.println ("Edit a user ... ");}}
3. Agent Class
Import Java.lang.reflect.invocationhandler;import java.lang.reflect.method;import java.lang.reflect.proxy;/** * * @author PC * */public class Serviceinvocationhandler implements Invocationhandler {//target object Private Object Targe T;public Serviceinvocationhandler (Object target) {super (); this.target = target;} /** * Create Proxy instance * @return * @throws throwable */public Object getproxy () throws Throwable {return proxy.newproxyinstance (thre Ad.currentthread (). Getcontextclassloader (), This.target.getClass (). Getinterfaces (), this);//This write only returns the target object, no proxy object is generated. //return target;} /** * Implement Invocationhandler interface Method * Execute the method of the target object and perform the Enhancement */public object Invoke (Object proxy, Method method, object[] args) throws T hrowable {Object result = null; SYSTEM.OUT.PRINTLN ("proxy class method, enhanced ... "); System.out.println ("Transaction begins ... ");//Execute Target Method Object result = Method.invoke (target, args); System.out.println ("End of transaction ... "); return result;}}
4. Test class
The public class Test {/** * JDK dynamic agent generates a dynamic proxy class, generates the appropriate bytecode, and then loads the bytecode via ClassLoader. * This instance inherits the proxy class, implements the business interface, and invokes the Invoke () callback method of the class * by reflection in the implemented method by using the Invocationhandler interface. * @param args * @throws throwable */public static void Main (string[] args) throws Throwable {UserService UserService = new Userserviceimpl (); Serviceinvocationhandler handler = new Serviceinvocationhandler (userservice);//Generate proxy object based on target UserService proxy = ( UserService) Handler.getproxy ();p roxy.adduser ();//proxy.edituser ();}}
5. Test results
Proxy class method, has been enhanced ... Transaction start ... Add a user ... End of transaction ...
Iv. cglib Dynamic Agent
Need to introduce the Cglib jar package,
In Pom.xml join dependency:
<!--https://mvnrepository.com/artifact/cglib/cglib--><dependency><groupid>cglib</groupid ><artifactId>cglib</artifactId><version>2.2.2</version></dependency>
1, business class, no implementation interface
/** * Business class * does not implement Interface * If the class is final, the proxy object cannot be generated, error. * If the method is final, the proxy is invalid * @author pc * */public class Userserviceimpl {public void AddUser () {System.out.println ("Add a user ... ");} public void Edituser () {System.out.println ("Edit a user ... ");}}
2. Agent Class
Import Java.lang.reflect.method;import Net.sf.cglib.proxy.enhancer;import net.sf.cglib.proxy.MethodInterceptor; Import net.sf.cglib.proxy.methodproxy;/** * Use cglib dynamic agent * @author pc * */public class Userservicecglib implements Methodin Terceptor{private Object target;/** * Create proxy instance * @param target * @return */public object getinstance (object target) {This.tar get = target; Enhancer enhancer = new Enhancer () Enhancer.setsuperclass (This.target.getClass ());//Set callback method Enhancer.setcallback ( this);//Create proxy object return Enhancer.create ();} /** * Implements the method to be overridden by the Methodinterceptor interface. * Callback method */public Object Intercept (Object obj, Method method, object[] Args,methodproxy proxy) throws Throwable { System . OUT.PRINTLN ("Transaction start ... "); Object result = Proxy.invokesuper (obj, args); System.out.println ("End of transaction ... "); return result;} }
3. Test class
public class Testcglib {public static void main (string[] args) {userservicecglib cglib = new Userservicecglib (); Userserviceimpl Bookfacadeimpl = (Userserviceimpl) cglib.getinstance (New Userserviceimpl ()); BookFacadeImpl.addUser ( );//bookfacadeimpl.edituser ();}}
4. Results:
Transaction start ... Add a user ... End of transaction ...
5. If the business implementation class is defined as the final class, the following error will be reported
Exception in thread "main" Java.lang.IllegalArgumentException:Cannot Subclass final Class class Cn.xx.xx.cgilb.UserServiceImplat Net.sf.cglib.proxy.Enhancer.generateClass (enhancer.java:446) at Net.sf.cglib.core.DefaultGeneratorStrategy.generate (DEFAULTGENERATORSTRATEGY.JAVA:25) at Net.sf.cglib.core.AbstractClassGenerator.create (abstractclassgenerator.java:216) at Net.sf.cglib.proxy.Enhancer.createHelper (enhancer.java:377) at Net.sf.cglib.proxy.Enhancer.create (Enhancer.java : 285) at Cn.pconline.proxy.cgilb.UserServiceCglib.getInstance (userservicecglib.java:30) at Cn.pconline.proxy.cgilb.TestCglib.main (Testcglib.java:7)
V. Summary
1. Principle
The implementation of the JDK static proxy is relatively simple, and the direct proxy object is generally wrapped directly by the proxy object.
The JDK dynamic agent is the interface agent, the proxy class A needs to implement the business interface, and the business proxy class B needs to implement the Invocationhandler interface.
The JDK dynamic agent generates an inherited proxy class based on the Proxied object and implements the JDK proxy class of the business interface, and the bytecode of that class is loaded into the ClassLoader, and the JDK proxy object instance is created.
When the JDK proxy object instance is created, the business proxy object instance is assigned to the proxy class, and the JDK proxy object instance has a business proxy object instance, and the JDK proxy object instance creates the corresponding method object m (possibly multiple) by reflection based on the business method of the proxy class. When the JDK proxy object instance invokes a business method, such as Proxy.adduser (), this will first pass the corresponding M object as a parameter to the Invoke () method (the second parameter of the Invoke method), invoking the Invoke () callback method of the JDK proxy object instance. The Invoke method is then invoked by reflection to invoke the proxy object because of the method, that is, result = Method.invoke (target, args);.
The Cglib dynamic agent is an inheritance agent, and the ASM bytecode framework modifies bytecode to generate new subclasses, overriding and enhancing the functionality of the method.
2. Advantages and Disadvantages
The JDK static proxy class can only serve a proxy class, and if there is more proxy analogy, it will produce too many proxy classes. The JDK static agent generates a class file at compile time, which can be used directly and efficiently without having to be generated at runtime.
The JDK dynamic agent must implement an interface that consumes system performance through reflection to dynamic proxy methods. However, there is no need to generate too many proxy classes to avoid duplication of code generation, the system more flexible.
Cglib dynamic agents do not need to implement interfaces, by generating sub-class bytecode to achieve, faster than reflection, no performance problems. However, because Cglib inherits the proxy class, it needs to rewrite the proxy method, so the proxy class cannot be the final class, and the proxy method cannot be final.
Therefore, the application of Cglib is more extensive.
Reference: http://blog.csdn.net/fighterandknight/article/details/51200470
http://blog.csdn.net/jiankunking/article/details/52143504
Java Proxy (JDK static agent, dynamic agent, and Cglib dynamic agent)