zoukankan      html  css  js  c++  java
  • AOP的底层实现,动态代理和cglib代理


    JDK动态代理
    public Object proxy(Object target){
    Object proxyInstance = Proxy.newProxyInstance(
    MyJDKProxyTransactionManager.class.getClassLoader(),
    target.getClass().getInterfaces(),
    new InvocationHandler() {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Object o = null;
    try {
    System.out.println("开启事物");
    jdbcConnectionUtils.openTx();
    o = method.invoke(target, args);
    jdbcConnectionUtils.commitAndClose();
    System.out.println("提交事物");
    return o;
    } catch (Exception e) {
    e.printStackTrace();
    jdbcConnectionUtils.rollbackAndClose();
    }
    return o;
    }
    }
    );
    return proxyInstance;
    }





    cglib代理
    public static void main(String[] args) {
    Enhancer enhancer = new Enhancer();
    MyCar myCar = new MyCar();
    enhancer.setSuperclass(myCar.getClass());
    enhancer.setCallback(new MethodInterceptor() {
    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
    Object o = null;
    try {
    System.out.println("cglib 代理前");
    o = method.invoke(myCar, args);
    System.out.println("cglib代理后");
    return o;
    } catch (Exception e) {
    e.printStackTrace();
    }
    return o;
    }
    });
    MyCar cglibCar = (MyCar) enhancer.create();
    cglibCar.jump();
    cglibCar.run();
    }


  • 相关阅读:
    51单片机学习1
    M41T11-RTC(实时时钟)
    ATmega8仿真——外部中断的学习
    C# 调用动态代码
    C# Attribute的用法
    DataTable相关
    addin1
    多线程信号源_红绿灯
    EF CodeFirst简单实例
    WCF配置Tcp协议
  • 原文地址:https://www.cnblogs.com/chenligeng/p/13179967.html
Copyright © 2011-2022 走看看