(接口 ArthmeticCalculator)············································接口
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);
}
(实现类 ArithmeticCalculatorlmp.java)·································实现类
package spring.aop.helloworld;
public class ArithmeticCalculatorlmp 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;
}
}
(代理类 ArithmeticCalculatorLoggingProxy.java)·························代理类
package 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 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 + "begin with" + Arrays.asList(args));
Object result = null;
try{
//前置通知 相当于 注解前置通知
Object result = method.invoke(target, args); //执行方法
//返回通知 相当于注解返回通知,当方法出错时,返回通知不执行
}catch(Exception e){
e.printStackTrace();
//异常通知:可以访问到方法出现的异常
}
//后置通知,因为方法可能会出异常,所以访问不到方法的返回值
//日志
System.out.println("the method" + methodname + "ends " + result);
return result;
}
};
proxy = (ArithmeticCalculator) Proxy.newProxyInstance(loader, interfaces, h);
return proxy;
}
public ArithmeticCalculatorLoggingProxy(ArithmeticCalculator target) {
super();
this.target = target;
}
}
(main)··························································Main
package spring.aop.helloworld;
public class Main {
public static void main(String[] args) {
ArithmeticCalculator target = new ArithmeticCalculatorlmp();
ArithmeticCalculator proxy = new ArithmeticCalculatorLoggingProxy(target).getLoggingProxy();
int result = proxy.add(4, 7);
System.out.println(result);
result = proxy.div(4, 1);
System.out.println(result);
}
}
打印