AOP底层实现原理:
首先定义一个接口Vehicle
1 2 3 4 5 6 7 8 9 10 11
| public class Car implements Vehicle{ @Override public void run() { System.out.println("Car正在run~~~"); }
@Override public String fly(int height) { return "Car飞行的高度为:" + height; } }
|
然后定义两个Car和Ship类去实现Vehicle接口
1 2 3 4 5 6 7 8 9 10 11
| public class Car implements Vehicle{ @Override public void run() { System.out.println("Car正在run~~~"); }
@Override public String fly(int height) { return "Car飞行的高度为:" + height; } }
|
1 2 3 4 5 6 7 8 9 10 11
| public class Ship implements Vehicle{ @Override public void run() { System.out.println("Ship正在run~~~"); }
@Override public String fly(int height) { return "Ship飞行的高度为:" + height; } }
|
最后定义VehicleProxyProvider返回一个代理对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| public class VehicleProxyProvider { private Vehicle target_vehicle;
public VehicleProxyProvider(Vehicle target_vehicle) { this.target_vehicle = target_vehicle; }
public Vehicle getProxy(){
ClassLoader classLoader = target_vehicle.getClass().getClassLoader();
Class<?>[] interfaces = target_vehicle.getClass().getInterfaces();
InvocationHandler invocationHandler = new InvocationHandler() {
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("全部开始运作咯~~~"); Object result = method.invoke(target_vehicle, args); System.out.println("全部停止运作咯~~~"); return result; } };
Vehicle proxy = (Vehicle) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
return proxy; }
|
这样我们就能够通过给VehicleProxyProvider传入一个Car对象或则Ship对象来返回一个代理对象,AOP就是在反射调用目标方法的前后去执行你所定义的代码,如图:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; try {
System.out.println("方法执行前-日志-方法名-" + method.getName() + "-参数" + Arrays.asList(args)); BellyAOP.before(proxy, method, args);
result = method.invoke(target_obj, args);
System.out.println("方法执行正常结束-日志-方法名-" + method.getName() + "-结果result=" + result);
} catch (Exception e) {
System.out.println("方法执行异常-日志-方法名-" + method.getName() + "-异常类型=" + e.getClass().getName()); throw new RuntimeException(e);
} finally {
System.out.println("方法最终结束-日志-方法名-" + method.getName());
} return result; }
|