Chapter 24 How much do you know about proxy knowledge in Spring AOP

Episode 1 Do you know dynamic proxy and static proxy

Introduction: Explain static proxy and dynamic proxy 

  • what is a proxy 
    • Create a proxy object for a certain object. The program does not directly use the original object, but the created proxy object controls the original object. Through the middle layer of the proxy class, the direct access to the delegate class object can be effectively controlled. , can also well hide and protect the entrusted class object, and also reserve space for implementing different control strategies
    • A ->B-> C
  •  What is a static proxy
    • The source code is created by the program or automatically generated by a specific tool. Before the program runs, the .class file of the proxy class already exists
  •  What is a dynamic proxy
    • When the program is running, it is dynamically created using the reflection mechanism, without the need to manually write code
      • JDK dynamic proxy
      • CGLIB dynamic proxy

Episode 2 Explanation of Static Agent in Actual Combat of Agent Mode 

Introduction: Explain the advantages and disadvantages of static proxy and practical operation
  • What is a static proxy
    • The source code is created by the program or automatically generated by a specific tool. Before the program runs, the .class file of the proxy class already exists
    • By implementing the same interface between the target class and the proxy class, let the proxy class hold the real class object, then call the real class method in the proxy class method, and add our The required function extension code to achieve the purpose of enhancement
    • A -> B -> C
  • advantage 
    • The proxy makes the client not need to know what the implementation class is and how to do it, and the client only needs to know the proxy
    • It is convenient to add functions and expand business logic
  • shortcoming 
    • There are a lot of redundant codes in the proxy class, which is very unfavorable for expansion and maintenance
    • If an interface adds a method, in addition to all implementation classes needing to implement this method, all proxy classes also need to implement this method. Increased complexity of code maintenance

PayService interface: (proxy class)

 

public interface PayService {

    String callback(String OutTradeNo);
    //根据用户和视频id进行存储
    int save(int userId ,int VideoId);
}

PayServiceImpl implementation class: (the proxy class implementation class)

ublic class PayServiceImpl implements PayService {
    public String callback(String OutTradeNo) {
        return OutTradeNo;
    }

    public int save(int userId, int VideoId) {
        //假设执行成功
        return 0;
    }
}

The static proxy implements the interface:

//静态实现类
public class StaticPayServiceImpl implements PayService {
    private PayService payService;
    public StaticPayServiceImpl(PayService payService){
        this.payService = payService;
    }
    public String callback(String OutTradeNo) {
        System.out.println("StaticPayServiceImpl callback begin");
       String result =  payService.callback(OutTradeNo);
        System.out.println(result);
        System.out.println("StaticPayServiceImpl callback end");
        return result;
    }

    public int save(int userId, int VideoId) {
        System.out.println("StaticPayServiceImpl save begin");
        int save = payService.save(userId, VideoId);
        System.out.println(save);
        System.out.println("StaticPayServiceImpl save end");
        return save;
    }
}

Test Methods:

  @Test
    public void Test(){

        StaticPayServiceImpl staticPayService = new StaticPayServiceImpl(new PayServiceImpl());
        staticPayService.callback("执行Callback");

        staticPayService.save(11,22);
    }

operation result:

Episode 3 AOP Implementation Strategy JDK Dynamic Proxy 

Introduction: Explain the common implementation strategies of AOP JDK dynamic proxy 

  • What is a dynamic proxy 
    • When the program is running, it is dynamically created using the reflection mechanism, without the need to manually write code
    • JDK dynamic proxy is the same as static proxy, the target class needs to implement a proxy interface , and then call the target method through the proxy object
  •  Practice:

Proxied class - target class:

public interface PayService {

    String callback(String OutTradeNo);
    //根据用户和视频id进行存储
    int save(int userId ,int VideoId);
}
public class PayServiceImpl implements PayService {
    public String callback(String OutTradeNo) {
        return OutTradeNo;
    }

    public int save(int userId, int VideoId) {
        //假设执行成功
        return 0;
    }
}

Dynamic proxy class: core code!

public class jdkProxy implements InvocationHandler {
    //目标类也就是被代理类
    private Object target;


    //获取代理类对象
    public Object newProxyInstace(Object target){
        this.target = target;
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),
                this);
    }

    //    使用jdk实现动态代理需要实现InvocationHandler并重写invoke方法
    public Object invoke(Object proxy, Method method, Object[] args)  {
        Object result = null;
        try{
            //增强处理
            System.out.println("通过动态代理调用"+method.getName()+"打印日志Begin");
            //执行目标类的方法
            result = method.invoke(target, args);
            System.out.println(result);
            System.out.println("通过动态代理调用"+method.getName()+"打印日志end");
        }catch (Exception e){

        }

        return result;
    }


}

Test class:

public class DongTaiProxy {
    public static void main(String[] args) {
        //测试动态代理
        //1.创建被代理类实现类 -目标类
        PayService payService = new PayServiceImpl();

        //2.创建jdkProxy对象
        jdkProxy jdkProxy = new jdkProxy();

        //3.使用jdkProxy对象创建动态代理 注意动态代理只能代理接口类型
        PayService DongTaiProxyPayService = (PayService)jdkProxy.newProxyInstace(payService);
        String result = DongTaiProxyPayService.callback("使用动态代理执行callback");


    }
}

operation result:

Episode 4 AOP Implementation Strategy CGLib Dynamic Proxy 

Introduction: Explain the common implementation strategies of AOP JDK dynamic proxy 

  • What is a dynamic proxy 
    • When the program is running, it is dynamically created using the reflection mechanism, without the need to manually write code
    • The principle of CgLib dynamic proxy is to generate a subclass for the specified business class, and override the business method in it to realize the proxy
  • Code
The delegated class is the same as Chapter 3
CGLib proxy class implementation: core code! Need to implement MethodInterceptor 
//基于Spring AOP包实现CGLib动态代理,需要导入Spring-core包
public class CGLibProxy implements MethodInterceptor {
    private Object target;
    public Object newProxyInstance(Object target){
        this.target = target;
        Enhancer enhancer = new Enhancer();

        //设置代理类的父类 (目标类)
        enhancer.setSuperclass(this.target.getClass());

        //设置回调函数,使用这个方法之后可以执行目标类的任何方法
        enhancer.setCallback(this);

        //创建子对象 (代理类对象)
        return enhancer.create();
    }
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
      Object result= null;
        try{
            //增强处理
            System.out.println("通过CGLib动态代理调用"+method.getName()+"打印日志Begin");
            //使用methodProxy执行父类的目标类方法
            result = methodProxy.invokeSuper(o,args);
            System.out.println(result);
            System.out.println("通过CGLib动态代理调用"+method.getName()+"打印日志end");
        }catch (Exception e){

        }
        return result;
    }

}

Test class:

   @Test
    public void CGLibTest(){
        //测试动态代理
        //1.创建被代理类实现类 -目标类
        PayService payService = new PayServiceImpl();

        //2.创建cgLibProxy对象
        CGLibProxy cgLibProxy = new CGLibProxy();

        //3.使用cgLibProxy对象创建动态代理 注意动态代理只能代理接口类型
        PayService DongTaiProxyPayService = (PayService) cgLibProxy.newProxyInstance(payService);
        String result = DongTaiProxyPayService.callback("使用动态代理执行callback");
    }

operation result:

Episode 5 Summary of CGLib Dynamic Proxy and JDK Dynamic Proxy 

Introduction: Summary of CGlib and JDk dynamic proxy 

  • Compared with static proxy, the biggest advantage of dynamic proxy is that all the methods declared in the interface are transferred to a centralized method of the call processor for decoupling and easy maintenance

 The difference between the two dynamic agents:

  • JDK dynamic proxy: the target object is required to implement an interface , but sometimes the target object is just a single object and does not implement any interface . At this time, CGLib dynamic proxy can be used
  • CGLib dynamic proxy , which builds a subclass object in memory to extend the function of the target object
  • JDK dynamic proxy is built-in, and CGlib needs to introduce a third-party package
  • CGLib dynamic proxy implements proxy based on inheritance, so proxy cannot be implemented for fifinal class, private method and static method

The default strategy used by proxies in Spring AOP :

  • If the target object implements the interface, JDK dynamic proxy is used by default
  • If the target object does not implement the interface, use CgLib for dynamic proxy
  • If the target object implements linking, the program can still specify the use of CGlib dynamic proxy

Guess you like

Origin blog.csdn.net/LiuJia20010827/article/details/126187297