current position:Home>Chapter 24 How much do you know about proxy knowledge in Spring AOP

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

2022-08-06 19:02:00LiuJia111222333

1集 Do you know dynamic proxy and static proxy

简介:Explain static proxy and dynamic proxy 

  • 什么是代理 
    • 为某⼀个对象创建⼀个代理对象,The procedure is not straightforward⽤原本的对象,⽽Is created by the proxy object to control the original object,Through the proxy class this middle⼀层,能有效控制对委托类对象的直接访问,也可以很好地隐藏和保护委托类对象,同时也为实施不同控制策略预留了空间
    • A ->B-> C
  •  什么是静态代理
    • Program-created or specific⼯具⾃动⽣into source code,在程序运⾏前,代理类的.class⽂item already exists
  •  什么是动态代理
    • 在程序运⾏时,运⽤反射机制动态创建⽽成,⽆需⼿Write code
      • JDK动态代理
      • CGLIB动态代理

2集 The static proxy explanation of the actual combat of the proxy mode 

简介:Explain the advantages, disadvantages and practical operation of static proxy
  • 什么是静态代理
    • Program-created or specific⼯具⾃动⽣into source code,在程序运⾏前,代理类的.class⽂item already exists
    • 通过将⽬The implementation of the standard class and the proxy class is the same⼀个接⼝,让代理类持有真实类对象,Then in the proxy class⽅法中调⽤真实类⽅法,在调⽤真实类⽅Add the function extension code we need before and after the method to achieve enhancement⽬的
    • A -> B -> C
  • 优点 
    • 代理使客户端不需要知道实现类是什么,怎么做的,⽽客户端只需知道代理即可
    • ⽅便增加功能,拓展业务逻辑
  • 缺点 
    • 代理类中出现⼤量冗余的代码,⾮常不利于扩展和维护
    • 如果接⼝增加⼀个⽅法,除了所有实现类需要实现这个⽅法外,所有代理类也需要实现此⽅法.增加了代码维护的复杂度

PayService接口:(被代理类)

 

public interface PayService {

    String callback(String OutTradeNo);
    //According to users and videosid进行存储
    int save(int userId ,int VideoId);
}

PayServiceImpl实现类:(The proxied class implements the class)

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

    public int save(int userId, int VideoId) {
        //Assume the execution is successful
        return 0;
    }
}

Static proxies implement the interface:

//Static implementation class
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
    public void Test(){

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

        staticPayService.save(11,22);
    }

运行结果:

3AOP的实现策略之JDK动态代理 

简介:讲解AOP常⻅implementation strategyJDK动态代理 

  • 什么是动态代理 
    • 在程序运⾏时,运⽤反射机制动态创建⽽成,⽆需⼿Write code
    • JDK动态代理与静态代理⼀样,⽬标类需要实现⼀个代理接⼝,再通过代理对象调⽤⽬标⽅法
  •  实操:

被代理类 - 目标类:

public interface PayService {

    String callback(String OutTradeNo);
    //According to users and videosid进行存储
    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) {
        //Assume the execution is successful
        return 0;
    }
}

动态代理类:核心代码!

public class jdkProxy implements InvocationHandler {
    //The target class is the proxy class
    private Object target;


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

    //    使用jdkImplementing dynamic proxies requires implementationInvocationHandler并重写invoke方法
    public Object invoke(Object proxy, Method method, Object[] args)  {
        Object result = null;
        try{
            //增强处理
            System.out.println("Called through a dynamic proxy"+method.getName()+"打印日志Begin");
            //执行目标类的方法
            result = method.invoke(target, args);
            System.out.println(result);
            System.out.println("Called through a dynamic proxy"+method.getName()+"打印日志end");
        }catch (Exception e){

        }

        return result;
    }


}

测试类:

public class DongTaiProxy {
    public static void main(String[] args) {
        //测试动态代理
        //1.Create the proxied class implementation class -目标类
        PayService payService = new PayServiceImpl();

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

        //3.使用jdkProxyObjects create dynamic proxies Note that dynamic proxies can only proxy interface types
        PayService DongTaiProxyPayService = (PayService)jdkProxy.newProxyInstace(payService);
        String result = DongTaiProxyPayService.callback("Execute using dynamic proxycallback");


    }
}

运行结果:

4AOP的实现策略之CGLib动态代理 

简介:讲解AOP常⻅implementation strategyJDK动态代理 

  • 什么是动态代理 
    • 在程序运⾏时,运⽤反射机制动态创建⽽成,⽆需⼿Write code
    • CgLib动态代理的原理是对指定的业务类⽣成⼀个⼦类,并覆盖其中的业务⽅法来实现代理
  • 代码实现
The proxied class is the same as in Chapter 3
CGLib代理类实现:核心代码! 需要实现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());

        //设置回调函数,Any method of the target class can be executed after using this method
        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");
            //使用methodProxyExecute the target class method of the parent class
            result = methodProxy.invokeSuper(o,args);
            System.out.println(result);
            System.out.println("通过CGLib动态代理调用"+method.getName()+"打印日志end");
        }catch (Exception e){

        }
        return result;
    }

}

测试类:

   @Test
    public void CGLibTest(){
        //测试动态代理
        //1.Create the proxied class implementation class -目标类
        PayService payService = new PayServiceImpl();

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

        //3.使用cgLibProxyObjects create dynamic proxies Note that dynamic proxies can only proxy interface types
        PayService DongTaiProxyPayService = (PayService) cgLibProxy.newProxyInstance(payService);
        String result = DongTaiProxyPayService.callback("Execute using dynamic proxycallback");
    }

运行结果:

5CGLib动态代理和JDK动态代理总结 

简介:总结CGlibJDk动态代理 

  • Dynamic proxies are the same as static proxies⽐较,最⼤The benefit is pick up⼝中声明的所有⽅法都被转移到调⽤处理器⼀个集中的⽅法中处理,解耦和易维护

 两种动态代理的区别:

  • JDK动态代理:要求⽬标对象实现⼀个接⼝,但是有时候⽬The target object is only⼀个单独的对象,Did not achieve any connection⼝,这个时候就可以⽤CGLib动态代理
  • CGLib动态代理,它是在内存中构建⼀个⼦class object from⽽实现对⽬An extension of the target object functionality
  • JDK动态代理是⾃带的,CGlib需要引⼊第三⽅包
  • CGLib动态代理基于继承来实现代理,所以⽆法对fifinal类、private⽅法和static⽅Act as an agent

Spring AOP中的代理使⽤的默认策略:

  • 如果⽬标对象实现了接⼝,则默认采⽤JDK动态代理
  • 如果⽬The target object does not implement a connection⼝,则采⽤CgLib进⾏动态代理
  • 如果⽬The target object realizes the connection,程序⾥⾯依旧可以指定使⽤CGlib动态代理

copyright notice
author[LiuJia111222333],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/218/202208061859101050.html

Random recommended