One article is enough for learning the Java agent model!

What is a dynamic proxy

Dynamic proxy is to enhance the method without modifying the source code.

Static proxy requires developers to manually write proxy classes to achieve enhancements to target classes

During the running of the program, the JVM virtual machine dynamically creates a proxy object. We can control the proxy object and enhance its methods.

Principle of Dynamic Agent

  • Dynamic proxy requires proxy class and target class to implement the same interface
  • Dynamic proxy based on reflection

The most soulful step in dynamic agency

Through the proxy object, the method of the target object is called based on reflection.

method.invoke(xiaoWang,args) ;

Composition of dynamic agent

Proxy object

target

Realization of dynamic proxy

  • Realization Technology of Dynamic Agent

      1. jdk 2. cglib
  • Implementation steps of dynamic proxy

    • Create interface
    • Create target class and target object
    • Create proxy object, no proxy class
    • Call the method of the proxy object, the proxy is successful
  • Dynamic proxy implementation

    • Proxy tool introduction

      static Object newProxyInstance( ClassLoader loader, Class<?>[] interfaces, InvocationHandler h);

      Three parameters

      The first parameter loader The loader of the target class (object)

      ​ xiaoWang.getClass().getClassLoader()

      The second parameter interfaces the interface array of the target class (object)

      ​ xiaoWang.getClass().getInterfaces()

      The third parameter h: processor interface, in this parameter, the target method is enhanced.

      ​ Two methods

      ​ One: Anonymous inner class

      ​ 2: Lambda expression

      ​ The dynamic agent is only enhanced by methods.

      ​ When implementing the third parameter, you need to rewrite the invoke method and enhance the target method in the invoke method

      ​ Object invoke(Object proxy, Method method, Object[] args)

      ​ The first parameter is the proxy object produced by the proxy tool class, xiaozhe

      ​ The second parameter method is the object of the currently executed method, based on reflection

      ​ The third parameter args The parameter array of the current execution method

@Test
public void versi() throws Exception {
    
    
    // 1.创建目标对象
    XiaoWang xiaoWang = new XiaoWang();
    // 2.通过Proxy工具类生产代理类和创建代理对象
    DancerInterface xiaozhe = (DancerInterface) Proxy.newProxyInstance(xiaoWang.getClass().getClassLoader(), xiaoWang.getClass().getInterfaces(), new InvocationHandler() {
    
    
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
            // 当前执行的方法名
            // System.out.println(method.getName());
            // 当前执行方法的参数
            // System.out.println(Arrays.toString(args));
            // 前置增强
            if ("dance".equals(method.getName())) {
    
    
                System.out.println("小哲去工作了");
            }
            // 由代理对象调用目标对象方法
            // method的意思是方法,它是方法对象
            Object result = method.invoke(xiaoWang, args);
 			
            // 后置增强
            if ("dance".equals(method.getName())) {
    
    
                result = "小王回到了家里," + result;
            }
            // 代理对象将结果返回给调用者
            return result;
        }
    });
    // 3.调用方法
    // 目标对象方法,不进行加强,简简单单的就相当于xiaoWang执行了这个方法.
    // String result = xiaoWang.dance("香泽菠菜");
    // 代理对象方法,已增强.
    String result = xiaozhe.dance("香泽菠菜");
    // 看看代理和不代理的区别
    System.out.println(result);
}

In the end, it must be the execution method of the proxy object.Through the reflection mechanism, the internal method of the proxy object enhancement method is still the original method of the target object to execute the target object.The enhanced function is enhanced in the invoke.

When the proxy object calls a method, there are three internal steps

1. Perform enhanced functions.

2. The target object executes the target object method.

2. Perform enhanced functions. That is, pre-enhanced or post-enhanced.

package com.qinghong.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class verwu {
    
    

    public static void main(String[] args) {
    
    

	 //	不使用代理增强
     //	Dancer dancer = new Xiaoqiang();
     //	dancer.dance();

        
     //  静态代理,Xiaozhe是自定义代理类,静态代理,两份代码同时写。
     //  Dancer dancer = new Xiaozhe();
     //  dancer.dance();

    
    //动态代理,动态的创建代理对象,不需要写实体代理类。
       // 创建目标对象
        Dancer dancer = new Xiaoqiang();
       /* 创建代理对象时要注意:
        	1、方法中传的三个参数,代理对象要跟目标对象在类加载器上和接口数组上保持一致,所以传的类加载器和接口数组都是目标对象的。
            2、类加载器,通过类加载器表明代理对象由哪个类加载器加载,要选用跟目标对象一样的类加载器,目标对象的类加载器,别装成猪了,你要装人。
            3、接口数组,通过跟目标对象一模一样的接口数组,你要装别人,你起码得知道别人长啥样,有啥衣服(方法)吧。
            4、处理器接口,增强的业务逻辑。*/
        Dancer xiaozhe = (Dancer)Proxy.newProxyInstance(dancer.getClass().getClassLoader(), dancer.getClass().getInterfaces(), new InvocationHandler() {
    
    
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
                //代理对象中,如何调用目标对象的方法。
                //你们猜,这个method是个啥玩意。
                System.out.println("你去卖烧烤吧");
                //这个方法,包含很多东西啊。
                Object obj = method.invoke(dancer, args);
                System.out.println("我不去");
                
                //方法对象有方法名,代理对象和目标对象是一个方法。
                //本质为让目标对象在这里调用它目标对象的方法.(重点!!!)
                //为什么代理对象执行这个方法就会发生反射?
                /*因为代理对象的这个方法就是在创建代理对象的过程中编写的
                执行这个方法时,自然要跑到上边创建代理对象的invoke方法中
                代理对象内部有一个大大的空间,这个空间里边有目标对象执行它目标对象方法的语句.
                代理对象类内部,动态代理没有物理上的代理类,需要虚拟代理类和目标类实现同一接口,创建代理对象时参数中前两个参数都是反射的基本条件。*/
                return obj;
            }
        });
        //代理对象调用方法
        xiaozhe.dance();
    }
}

Simple understanding of proxy mode

The proxy object is to wrap the proxy object in one layer, and do some extra work inside it. For example, the user needs to go to Facebook, but the ordinary network cannot directly access it. The network proxy helps the user to cross the wall first, and then visit Facebook. This is the role of the agent.

Remote proxy: We cannot access facebook because of GFW in China. We can use the method of overcoming the wall (setting proxy) to access. The access process is:
(1) The user sends an HTTP request to the agent.
(2) The proxy sends the HTTP request to the web server.
(3) The web server sends the HTTP response to the proxy.
(4) The proxy sends the HTTP response back to the user.

The difference between static and dynamic

Static proxy

​ The programmer creates the proxy class or a specific tool automatically generates the source code and then compiles it. The .class file of the proxy class exists before the program runs.

Advantages: The proxy makes the client do not need to know what the specific implementation class is and how to do it, only need to know the proxy (decoupling)

Disadvantages:

​ 1.The target class implements this method, and the proxy class must also implement this method, and the code is repeated.

If the interface adds a method, all implementation classes need to rewrite this method (this interface cannot be customized for one implementation class for one method, it must have multiple implementation classes), and all proxy classes also need to be rewritten like this The method increases the complexity of code maintenance.

​ 2. The proxy object only serves one type of object. If you want to serve multiple types of objects, it is bound to be a proxy for each type of object. The static proxy will not be competent when the program scale is slightly larger. If you want to If other classes provide proxies, we need to add other proxy classes again.

​ That is, the static proxy class can only serve a specific interface (Service). If you want to serve multiple interfaces, you need to create many proxy classes. If you want to use a proxy class to complete all the proxy functions, you need to use a dynamic proxy.

Dynamic proxy

​ It is dynamically created by the reflection mechanism when the program is running. When the program is running, the reflection mechanism is used to realize dynamic proxy, and it can proxy various types of objects. JAVA program we follow the OCP (open for extension, closed for modification) principle (open and close principle), and it is the practice of AOP thought.

advantage:

​ Compared with static proxy, the biggest advantage of dynamic proxy is that all methods declared in the interface are transferred to a centralized method of the invocation handler (InvocationHandler.invoke). In this way, when the number of interface methods is relatively large, we can Flexible processing, without the need to transfer every method like a static proxy. And the application of dynamic proxy makes our class responsibilities more single and more reusable.

The difference between dynamic proxy and static proxy

​ Usage: Static proxy needs to write proxy class manually

​ Functionally: static proxy proxy one type, dynamic proxy proxy multiple types

The actual business difference between dynamic agent and static agent

Give a small example

Static proxy, each method in this interface implemented by the proxy class needs to add logging code

For dynamic agents, you only need to add logging code to the invoke() method to add logging to each method.

·················································································

Did you lose school?

Guess you like

Origin blog.csdn.net/numbbe/article/details/109271061