Spring之代理模式实例
Posted 叮咚叮咚
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring之代理模式实例相关的知识,希望对你有一定的参考价值。
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之代理模式实例的主要内容,如果未能解决你的问题,请参考以下文章