spring aop原理 InvocationHandler Proxy

spring aop是基于spring IOC容器来管理以及使用了JDK自身的动态代理来实现,程序运行时在被切面前后动态进行的一些逻辑处理。

1 package com.daosheng.component; java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 import java.lang.reflect.Proxy; * JDK动态代理的实现 8 * 实现InvocationHandler接口,重写invoke方法 fanghb10 *LogIntercepter implements InvocationHandler{* 声明目标对象也就是被代理对象 Object target;* 获得代理对象,20 * 这个代理对象是由传入的接口类型动态构造出来的一个代理类实例类型,,21 * 这个代理类是JVM在内存中动态构造的动态类22 * 23 * tar.getClass().getClassLoader() 代理类加载器需和目标对象类加载器一致24 * tar.getClass().getInterfaces()代理对象需实现目标对象所实现的接口25 * this调用此方法对象本身 tar被代理对象 Object getProxy(Object tar) {30this.target = tar;31Object proxy = Proxy.newProxyInstance(tar.getClass().getClassLoader(),32tar.getClass().getInterfaces(), this);33return proxy;34 }* 此方法在被代理对象的方法被调用之前触发,38 * 可以对被代理类方法调用的前后进行一些逻辑处理39 * proxy代理对象 method当前被调用的方法 args当前被调用的方法参数 @Override45public Object invoke(Object proxy, Method method, Object[] args)46throws Throwable {47Object result = null; {} catch (Exception e) {52 e.printStackTrace();53 } result;56 }* 被代理类方法调用前后的逻辑处理60 * m当前被调用的方法before(Method method) {System.out.println(“织入预处理逻辑到” + method.getName() + “方法”);65 }after(Method method) {System.out.println(“织入后处理逻辑到” + method.getName() + “方法”);68 }69 70 }欲望以提升热忱,毅力以磨平高山。

spring aop原理 InvocationHandler Proxy

相关文章:

你感兴趣的文章:

标签云: