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


  • 相关阅读:
    技术检验
    Linux 系统命令总结
    ftp服务器的搭建
    Win10优秀软件推荐
    Mac软件推荐
    博客主题美化
    无人机开发之四:Pixhawk开发环境搭建
    无人机开发之三:飞行器入门理论知识
    无人机开发之二:Pixhawk硬件架构
    无人机开发之一:Pixhawk与Arduino简述
  • 原文地址:https://www.cnblogs.com/chenligeng/p/13179967.html
Copyright © 2011-2022 走看看