Spring學習-day09

動態代理:
Spring學習-day09 java

package com.atguigu.spring.aop.helloworld;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class ArithmeticCalculatorLoggingProxy {

    //要代理的對象
    private ArithmeticCalculator target;

    public ArithmeticCalculatorLoggingProxy(ArithmeticCalculator target) {
        this.target = target;
    }

    public ArithmeticCalculator  getLoggingProxy() {
        ArithmeticCalculator proxy = null;

        //代理對象由哪個類加載器負責加載
        ClassLoader loader = target.getClass().getClassLoader();
        //代理對象的類型,即其中有哪些方法
        Class[] interfaces = new Class[]{ArithmeticCalculator.class};

        //當調用代理對象其中的方法時, 該執行的代碼
        InvocationHandler h = new InvocationHandler() {
            /**
             * proxy: 正在返回的那個代理對象, 通常狀況下, 在 invoke 方法中都不使用該對象
             * method: 正在被調用的方法
             * args: 調用方法時, 傳入的參數
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) 
                    throws Throwable {
                String methodName = method.getName();
                //日誌
                System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
                //執行方法
                Object result = method.invoke(target, args);
                //日誌
                System.out.println("The method " + methodName + " ends with " + result);
                return result;
            }
        };
        proxy = (ArithmeticCalculator) Proxy.newProxyInstance(loader, interfaces, h);

        return proxy;
    }
}
package com.atguigu.spring.aop.helloworld;

public class ArithmeticCalculatorImpl implements ArithmeticCalculator {

    @Override
    public int add(int i, int j) {

        int result = i + j;
        return result;
    }

    @Override
    public int sub(int i, int j) {

        int result = i - j;
        return result;
    }

    @Override
    public int mul(int i, int j) {

        int result = i * j;
        return result;
    }

    @Override
    public int div(int i, int j) {

        int result = i / j;
        return result;
    }

}
package com.atguigu.spring.aop.helloworld;

public interface ArithmeticCalculator {
    //加減乘除
    int add(int i, int j);
    int sub(int i, int j);

    int mul(int i, int j);
    int div(int i, int j);
}
package com.atguigu.spring.aop.helloworld;

public class Main {
    public static void main(String[] args) {
//      ArithmeticCalculatorImpl arithmeticCalculatorImpl = new ArithmeticCalculatorImpl();

        ArithmeticCalculator target = new ArithmeticCalculatorImpl();
        ArithmeticCalculator proxy = new ArithmeticCalculatorLoggingProxy(target).getLoggingProxy();

        int result = proxy.add(1, 2);
        System.out.println("-->" + result);

        result = proxy.div(4, 2);
        System.out.println("-->" + result);
    }
}
相關文章
相關標籤/搜索