Agent Mode Introduction
Proxy mode is a kind of common design pattern, its function is to provide the target object with additional access mode, without modifying the target object's premise, extend the target object's additional functions, such as statistics execution time, print log and so on.
There are two types of proxy modes: static agents and dynamic proxies.
Requirements: If you do not want to change the original code situation, and record the user Save method execution time. The sample code is as follows:
Interface
public interface UserService { public void saveUser(User user);}
Implementation class
public class UserServiceImpl implements UserService { private UserDao userDaoImpl; @Override public void saveUser(User user) { userDaoImpl.save(user); } ...}
Static proxy implementations
Static proxies are generated before the program is run, in general, the proxy class and the target class implement the same interface or have the same parent class
proxy class
public class UserServiceProxyImpl implements UserService { private UserService UserServiceImpl;//代理类持有一个委托类的对象引用 public UserServiceProxyImpl(UserService UserServiceImpl) { this.UserServiceImpl = UserServiceImpl; } @Override public void saveUser(User user) { long startTime = System.currentTimeMillis(); System.out.println("开始记录时间"); delegate.dealTask(taskName); // 将请求分派给委托类处理 long endTime = System.currentTimeMillis(); System.out.println("保存用户信息方法耗时" + (endTime-startTime) + "毫秒"); }}
Static factory class that produces proxy objects
public class UserServiceProxyFactory { public static UserService getInstance() { return new UserServiceProxyImpl(new UserServiceImpl()); }}
Client
public class ClientTest { public static void main(String[] args) { UserService UserServiceProxy = UserServiceProxyFactory.getInstance(); UserServiceProxy.saveUser(new User("1","张三")); }}
Run results
开始记录时间保存用户信息方法耗时0.01毫秒
Static agent Advantages and disadvantages:
Advantages:
1, Business class Userserviceimpl only need to pay attention to the business logic itself, to ensure the reuse of business class.
2. There is no direct dependency between client and business class Userserviceimpl, and the specific implementation is blocked for customers.
Disadvantages:
1. An interface of a proxy object serves only an object of an interface type, and static agents cannot be used when the program size is slightly larger.
2, if the interface adds a method, in addition to all implementation classes need to implement this method, all proxy classes also need to implement this method. Added complexity of code maintenance
Dynamic Proxy Implementation
Dynamic agent is a proxy object that the program generates dynamically within the JVM during running, and the proxy class can implement the proxy for many kinds of classes.
Dynamic agent is divided into two kinds: JDK dynamic agent and Cglib dynamic agent.
JDK Dynamic Agent
The JDK dynamic agent must first declare an intermediate class between the proxy class and the target class, which needs to implement an interface Invocationhandler in the JDK. The source code is as follows:
package java.lang.reflect;public interface InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;}
Intermediate classes that produce proxy objects
Import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;import Java.lang.reflect.proxy;public Class Jdkproxy implements Invocationhandler {private object target;//The reference to the target object is held by public Jdkproxy (object target) { This.target = target; }//Create proxy Object public Object Createproxy () {//1. Get the target object's ClassLoader ClassLoader ClassLoader = TARGET.GETCL (). getClassLoader (); 2. Get the implementation interface of the target object class[] class<?>[] interfaces = Target.getclass (). Getinterfaces (); 3. The third parameter requires an object//3-1 that implements the Invocationhandler interface. The first one, let the current class implementation Invocationhandler, the third parameter write this return proxy.newproxyin Stance (ClassLoader, interfaces, this); 3-2. The second way of writing, the third parameter in the form of an anonymous inner class, first commented out/*return proxy.newproxyinstance (ClassLoader, interfaces, new Invocationhandler () { @Override public Object Invoke (object proxy, Method method, object[] args) throws Throwable { Long startTime = System.currenttimemillis (); System.out.println ("Start recording Time"); Object ret = Method.invoke (target, args); Executes the target object method, where the target is written if the Write proxy will die looping until memory overflows long endTime = System.currenttimemillis (); System.out.println ("Save user Information Method Time" + (Endtime-starttime) + "millisecond"); return ret; }}); */* The method parameter for executing the target object on the proxy instance 1 is the proxy object, generally does not use the parameter 2 of the method that it calls methods object parameter 3 parameter of method called */@Overri De public object Invoke (object proxy, Method method, object[] args) throws Throwable {Long startTime = SYSTEM.C Urrenttimemillis (); System.out.println ("Start recording Time"); Object ret = Method.invoke (target, args);//Executes the target object method, where it writes target if the Write proxy will die loop until memory overflows long endTime = System.currenttimemi Llis (); System.out.println ("Save user Information Method Time" + (Endtime-starttime) + "millisecond"); return ret; }}
Client
public class ProxyTest { @Test public void test1() { UserService userService = new UserServiceImpl(); //1.创建目标对象 JDKProxy factory = new JDKProxy(userService); // 2.通过JKDProxy完成代理对象创建 UserService userServiceProxy = (UserService)factory.createProxy(); userServiceProxy.saveUser(new User("1","张三")); }}
Two points to focus on in the JDK dynamic agent:
1, Proxy.newproxyinstance (ClassLoader, interfaces, this); How the underlying proxy object is created
2. When the Invoke method is executed, who will call this method
<font color=red> parsing 1>></font> How to produce proxy objects:
@CallerSensitivepublic static Object newproxyinstance (ClassLoader loader,class<?>[] interfaces, Invocationhandler h) throws IllegalArgumentException {if (h = = null) {throw new NullPointerException (); } final class<?>[] Intfs = Interfaces.clone (); Final SecurityManager sm = System.getsecuritymanager (); if (SM! = null) {checkproxyaccess (Reflection.getcallerclass (), loader, intfs); }/* * Look up or generate the designated proxy class. */class<?> CL = GETPROXYCLASS0 (loader, intfs); /* * Invoke its constructor with the designated invocation handler. */try {final constructor<?> cons = Cl.getconstructor (constructorparams); Final Invocationhandler ih = h; if (SM! = null && Proxyaccesshelper.needsnewinstancecheck (CL)) {//Create proxy instance with Doprivil Ege as the proxy class may//implement Non-public interfaces that requires a special permission Return accesscontroller.doprivileged (New privilegedaction<object> () {public Object run () { Return Newinstance (cons, IH); } }); } else {return newinstance (cons, IH); }} catch (Nosuchmethodexception e) {throw new Internalerror (e.tostring ()); }}//continue to see Newinstance method private static Object newinstance (constructor<?> cons, Invocationhandler h) {try {re Turn cons.newinstance (new object[] {h}); } catch (Illegalaccessexception | Instantiationexception e) {throw new Internalerror (e.tostring ()); } catch (InvocationTargetException e) {throwable t = e.getcause (); if (t instanceof RuntimeException) {throw (runtimeexception) t; } else {throw new Internalerror (t.tostring ()); } }}
It can be seen that the proxy object is created by using reflection to get the constructor of the target object first, and then the proxy object is generated by constructing the reflection
<font color=red> parsing 2>></font>invoke method is called when:
We use a tool class to output the bytecode of the generated proxy object to disk, and then decompile to see what the proxy object is
The tool classes are as follows:
public class ProxyGeneratorUtils { /** * 把代理类的字节码写到硬盘上 * @param fileName 文件名 * @param path 路径信息 * @param clazz 目标类的接口数组 */ public static void writeProxyClassToHardDisk(String fileName, String path, Class<?>[] clazz) { byte[] classFile = ProxyGenerator.generateProxyClass(fileName, clazz); FileOutputStream out = null; try { out = new FileOutputStream(path); out.write(classFile); out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } //主方法 public static void main(String[] args) { ProxyGeneratorUtils.writeProxyClassToHardDisk("$JDKProxy1","F:/$JDKProxy1.class",UserServiceImpl.class.getInterfaces()); }}
Run the main method to generate the proxy object bytecode file, which is opened with JD.exe Decompile as follows
public final class $JDKProxy1 extends Proxy implements UserService { private static Method m1; private static Method m3; private static Method m0; private static Method m2; public $JDKProxy1(InvocationHandler arg0) throws { super(arg0); } public final void saveUser(User arg0) throws { try { super.h.invoke(this, m3, new Object[]{arg0}); } catch (RuntimeException | Error arg2) { throw arg2; } catch (Throwable arg3) { throw new UndeclaredThrowableException(arg3); } } ...
Use a graph to illustrate what happens inside the Saveuser () method that invokes the Userserviceproxy proxy object
Cglib Dynamic Agent
The cglib dynamic proxy also needs an intermediate class that generates the proxy object, which implements the Methodinterceptor interface, which is now integrated in the Cglib package and is currently in the Spring-core core package <br>
Intermediate classes that produce proxy objects
Import Java.lang.reflect.method;import Org.springframework.cglib.proxy.enhancer;import Org.springframework.cglib.proxy.methodinterceptor;import Org.springframework.cglib.proxy.methodproxy;public Class Cglibproxy implements Methodinterceptor {private object target;//The reference to the target object is held by public Cglibproxy (object target) { This.target = target; }//Create proxy Object public Object Createproxy () {Enhancer enhancer = new enhancer ();//1. Create Enhancer enhancer.se Tsuperclass (Target.getclass ()); 2. Pass the target object's class Enhancer.setcallback (this); 3. Set callback operation (equivalent to Invocationhanlder) return enhancer.create (); }//equivalent to invoke @Override public object intercept in Invocationhanlder (object proxy, method, object[] args, Me Thodproxy methodproxy) throws Throwable {Long startTime = System.currenttimemillis (); System.out.println ("Start recording Time"); Object ret = Method.invoke (target, args);//Executes the target object method, where it writes target if the Write proxy will die loop until memory overflows long endTime = System.curreNttimemillis (); System.out.println ("Save user Information Method Time" + (Endtime-starttime) + "millisecond"); return ret; }}
Client
public class ProxyTest { @Test public void test1() { UserService userService = new UserServiceImpl(); //1.创建目标对象 CglibProxy factory = new CglibProxy(customerService); // 2.通过CglibProxy完成代理对象创建 UserService userServiceProxy = (UserService)factory.createProxy(); userServiceProxy.saveUser(new User("1","张三")); }}
Generate the proxy object bytecode, and decompile the JD.exe as follows
import java.lang.reflect.Method;import org.springframework.cglib.core.ReflectUtils;import org.springframework.cglib.core.Signature;import org.springframework.cglib.proxy.Callback;import org.springframework.cglib.proxy.Factory;import org.springframework.cglib.proxy.MethodInterceptor;import org.springframework.cglib.proxy.MethodProxy;public class UserServiceImpl$$EnhancerByCGLIB$$1772a9ea extends UserServiceImpl implements Factory { ... public final void saveUser(User paramUser) { MethodInterceptor tmp4_1 = this.CGLIB$CALLBACK_0; if (tmp4_1 == null){ tmp4_1; CGLIB$BIND_CALLBACKS(this); } if (this.CGLIB$CALLBACK_0 != null) return; super.saveUser(paramUser); } ...}
JDK Dynamic agent and Cglib dynamic agent differences:
1, the JDK dynamic agent is for the interface agent, the target class must implement the interface, the resulting proxy object will also implement the interface.
2, Cglib Proxy is inherited, the resulting proxy object inherits from the target class, so the target class and the target method can not be modified with the final.
The popular understanding of dynamic agent in Java