zoukankan      html  css  js  c++  java
  • JDK动态代理

    Spring的AOP实现用了Proxy和InvocationHandler,现在就介绍一下JDK动态代理。

    自定义的InvocationHandler需要重写3个函数。

      1)构造函数,将代理对象传入

      2)invoke方法

      3)getProxy方法

    1、创建业务接口

    public interface UserService{

      public void add();

    }

    2、创建业务接口实现类

    public class UserServiceImpl implements UserService{

      public void add(){

        System.out.println("-----add-----");

      }

    }

    3、创建自定义的InvocationHandler

    public class MyInvocationHandler implements InvocationHandler{

      //目标对象

      private Object target;

      public MyInvocationHandler(Object target){

        super();

        this.target=target;

      }

    4、执行目标对象的方法

    public Object invoke(Object proxy, Method method, Object [] args)throws Throwable {

        System.out.println("-----before-----");

        Object result=method.invoke(target,args);

        System.out.println("----after-----");

      }

    5、获取目标对象的代理对象

    public Object getProxy(){

      return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),target.Class.getInstance(),this);

      }

    }

    6、测试代理

    public class ProxyTest{

    @Test

    public void testProxy()throws Throwable{

      //实例化目标对象

      UserService userService=new UserServiceImpl();

      //实例化InvocationHandler

      MyInvocaitonHanlder invovationHandler=new MyInvocationHandler(userService);

      //根据目标对象生成代理对象

      UserService proxy=(UserService) invocationHandler.getProxy();

      //调用代理对象的方法

      proxy.add();

      }

    }

    7、测试结果

    ------before------

    ------add--------

    ------after-------

  • 相关阅读:
    Vue父子组件传值$parent , ref,$refs,props大总结
    Vue-axios
    tensorflow2知识总结(杂)---1、安装tensorflow
    线性回归和逻辑回归的区别
    %matplotlib inline的含义
    王阳明的心学到底是啥
    Windows Anaconda 修改为国内源
    Reporting Services Single Sign On (SSO) Authentication
    .NET
    WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)
  • 原文地址:https://www.cnblogs.com/jigang/p/12950966.html
Copyright © 2011-2022 走看看