类接口:
package com.spring.aop;
public interface ArithmeticCalculator {
public int add(int i,int j);
public int sub(int i,int j);
public int mul(int i,int j);
public int div(int i,int j);
}
接口实现类
package com.spring.aop;
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
@SuppressWarnings("unused")
@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.spring.aop;
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;
//告诉类加载器代理对象proxy由哪个类加载器加载
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("方法 "+methodName+" 开始执行,参数:"+Arrays.asList(args));
//执行被代理的对象的方法
Object result = method.invoke(target, args);
//日志输出
System.out.println("方法 "+methodName+" 结束执行,结果:"+result);
return result;
}
};
proxy = (ArithmeticCalculator) Proxy.newProxyInstance(loader, interfaces, h);
return proxy;
}
}
main方法类:
package com.spring.aop;
public class Main {
public static void main(String[] args) {
ArithmeticCalculator target = new ArithmeticCalculatorImpl();
ArithmeticCalculator proxy = new ArithmeticCalculatorLoggingProxy(target).getLoggingProxy();
int result = proxy.add(1, 2);
System.out.println("-->"+result);
}
}