-- Spring AOP的根基是动态代理。(或者说动态AOP的根基是动态代理,这种AOP会在程序运行过程中在内存中生成代理类的字节码。AspectJ在编译阶段就会将Advice一同编译进Target,属于静态AOP)
-- 动态代理有两种方式:
-- JDK动态代理:需要被代理类实现接口
-- CGLIB动态代理:通过继承方式实现,不需要实现接口
-- 下面的内容,从JDK动态代理的使用到其实现原理做了研究。
-- JDK动态代理中涉及到了Java的Reference类: java.lang.ref.Reference 。对于 Reference类在别的文章中另做总结。
-- 先看如何使用:
执行结果如下:
------------------before------------------
--------------------add---------------
-------------------after------------------
用起来是很简单吧,其实这里基本上就是AOP的一个简单实现了,在目标对象的方法执行之前和执行之后进行了增强。Spring的AOP实现其实也是用了Proxy和InvocationHandler这两个东西的。
-- 动态代理有两种方式:
-- 下面的内容,从JDK动态代理的使用到其实现原理做了研究。
-- JDK动态代理中涉及到了Java的Reference类: java.lang.ref.Reference 。对于 Reference类在别的文章中另做总结。
-- 先看如何使用:
Java代码
- package
dynamic.proxy; -
- import
java.lang.reflect.InvocationHandler; - import
java.lang.reflect.Method; - import
java.lang.reflect.Proxy; -
-
- public
class MyInvocationHandler implements InvocationHandler { -
-
// 目标对象 -
private Object target; -
-
-
public MyInvocationHandler(Object target) { -
super(); -
this.target = target; -
} -
-
-
-
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { -
-
// 在目标对象的方法执行之前简单的打印一下 -
System.out.println("------------------before------------------"); -
-
// 执行目标对象的方法 -
Object result = method.invoke(target, args); -
-
// 在目标对象的方法执行之后简单的打印一下 -
System.out.println("-------------------after------------------"); -
-
return result; -
} -
-
-
public Object getProxy() { -
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), -
target.getClass().getInterfaces(), this); -
} - }
-
- package
dynamic.proxy; -
-
- public
interface UserService { -
-
-
public abstract void add(); -
- }
-
- package
dynamic.proxy; -
-
- public
class UserServiceImpl implements UserService { -
-
-
public void add() { -
System.out.println("--------------------add---------------"); -
} - }
-
- package
dynamic.proxy; -
- import
org.junit.Test; -
-
- public
class ProxyTest { -
-
@Test -
public void testProxy() throws Throwable { -
// 实例化目标对象 -
UserService userService = new UserServiceImpl(); -
-
// 实例化InvocationHandler -
MyInvocationHandler invocationHandler = new MyInvocationHandler(userService); -
-
// 根据目标对象生成代理对象 -
UserService proxy = (UserService) invocationHandler.getProxy(); -
-
// 调用代理对象的方法 -
proxy.add(); -
-
} - }
执行结果如下:
------------------before------------------
--------------------add---------------
-------------------after------------------