码迷,mamicode.com
首页 > 编程语言 > 详细

Spring之代理模式实例

时间:2019-03-07 12:57:37      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:interface   public   静态   rtt   动态   mem   star   tproxy   exce   

1、静态代理

2、动态代理

public interface Math {
    public int div(int a, int b) throws Exception;
}

@Component
public class MathCaculator implements Math {
    public MathCaculator() {
        System.out.println("MathCaculator构造器***************");
    }
    public int div(int a, int b) throws Exception {
        System.out.println("除法的方法主体");
        return a/b;
    }
}

public class DynamicProxy implements InvocationHandler {
    Object targetObject;

    public Object getProxyObejct(Object targetObject) {
        this.targetObject = targetObject;
        return Proxy.newProxyInstance(targetObject.getClass().getClassLoader()
                ,targetObject.getClass().getInterfaces(),this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        long startTime = System.currentTimeMillis();
        Thread.sleep(100);
        Object result=method.invoke(targetObject, args);
        long endTime = System.currentTimeMillis();
        System.out.println("耗时"+(endTime-startTime)+"秒");
        System.out.println("结果+"+result);
        return result;
    }
}


public class Test {
    public static void main(String[] args) throws Exception {
        Math math = (Math) new DynamicProxy().getProxyObejct(new MathCaculator());
        math.div(10,5);
    }
}

  

 

Spring之代理模式实例

标签:interface   public   静态   rtt   动态   mem   star   tproxy   exce   

原文地址:https://www.cnblogs.com/yaohuiqin/p/10488853.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!