目录

AOP也叫面向切面编程,常用于以下场景调用函数之前,之后触发其他工作,常用于权限验证,或记录日志

创建一个接口,AOP依赖借口

public interface Calculator {
    public abstract void sum(int a,int b);
    public abstract void sub(int a,int b);
}

实现接口

public class CalculatorImpl implements Calculator {
    public void sum(int a,int b) {
        System.out.println(a+b);
    }
    public void sub(int a,int b) {
        System.out.println(a-b);
    }
}

创建代理类

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


/**
 * 创建一个代理对象.调用时只调用代理,由代理去操作真实对象
 */
public class Proxyer implements InvocationHandler {

    private Object tarjectObject;

    public Object getProxy(Object obj) {
        this.tarjectObject = obj;
        return Proxy.newProxyInstance(this.tarjectObject.getClass()
                .getClassLoader(), this.tarjectObject.getClass()
                .getInterfaces(), this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("begin");
        Object ret = method.invoke(tarjectObject,args);
        System.out.println("end");
        return ret;
    }
}

主函数


public class App {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Proxyer factory = new Proxyer();
        Calculator psersonServiceBean = new CalculatorImpl();
        Calculator service=(Calculator)factory.getProxy(psersonServiceBean);
        service.sum(1,2);
        service.sub(1,2);
    }

}

输出

begin
3
end
begin
-1
end