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

  

猜你喜欢

转载自www.cnblogs.com/yaohuiqin/p/10488853.html