摘录地址:
http://jamesby.javaeye.com/blog/71036
用Spring大概有3个月,一直都是张口AOP,闭口AOP,但是Spring的AOP具体是怎么实现的,现在也不是十分清楚.
只知道可以用JDK的动态代理,基于接口,或者是cglib方式字节码增强.目前对JDK的动态代理方式不是很理解,固拿出来探讨下,我知道这应该是个新手贴,但还是请大家给点意见.如果真正理解了动态代理,那么对基于Spring AOP出现的各种现象就比较容易理解了.
先贴上一段代码.
代码
- package com.jamesby.proxy;
- public interface CarCompany {
-
- public void makeCar();
- public void abc();
- }
-
- package com.jamesby.proxy;
-
- public class CarCompanyImpl implements CarCompany {
- public void makeCar() {
- System.out.println("Company A make a car!");
- abc();
- }
- public void abc()
- {
- System.out.println("abc is invoked!");
- }
- }
-
- package com.jamesby.proxy;
-
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
-
- public class CarCompanyHandler implements InvocationHandler {
- CarCompany com;
- //构造时将被代理类绑定到Handler
- public CarCompanyHandler(CarCompany com) {
- this.com = com;
- }
-
- /**相当于要把代理类的执行方法重新包装
- *proxy:被代理类
- *method:被代理类要执行的方法
- *args:被代理类要执行的方法时需要的参数
- **/
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- System.out.println("time1:" + System.currentTimeMillis());
- method.invoke(this.com, new Class[] {});
- System.out.println("time2:" + System.currentTimeMillis());
- return null;
- }
- }
-
- package com.jamesby.proxy;
-
- import java.lang.reflect.Proxy;
-
- public class Test {
- public static void main(String[] arg) {
- CarCompanyImpl a = new CarCompanyImpl();
- //将被代理类绑定到handler
- CarCompanyHandler handler = new CarCompanyHandler(a);
-
- CarCompany com = (CarCompany) Proxy.newProxyInstance(Test.class
- .getClassLoader(), new Class[] { CarCompany.class }, handler);
- com.makeCar();
- }
- }