• 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();
    }


  • 相关阅读:
    学校的SQLServer的笔记
    Javaの集合学习
    XML的学习
    Java中学校没学过的东西
    MySQL的学习
    牛顿法及其收敛性
    c++编码规范
    C++标准库
    MATLAB编程技巧
    Matlab学习记录(函数)
  • 原文地址:https://www.cnblogs.com/chenligeng/p/13179967.html
Copyright © 2020-2023  润新知