JDK动态代理——Spring AOP原理简单模拟
主要涉及的类和接口有:java.lang.reflect包下的Proxy类和InvocationHandler接口
接口InvocationHandler中就一个方法,
Object invoke(Object proxy, Method method, Object[] args)
通过实现该接口,可以在原有方法的基础上添加一些业务逻辑,即AOP
而Proxy为InvocationHandler实现类动态创建一个符合某一接口的代理实例。
看如下代码:
接口MyService
package wen.hui.proxy; public interface MyService { public void add(); public void remove(); }
接口的实现类MyServiceImpl
package wen.hui.proxy; public class MyServiceImpl implements MyService { @Override public void add() { //do something... try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("add success..."); } @Override public void remove() { //do something... try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("remove success..."); } }
实现InvocationHandler的类MyHandler
package wen.hui.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class MyHandler implements InvocationHandler { private Object target; public MyHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { long start = System.currentTimeMillis(); Object obj = method.invoke(target, args); long end = System.currentTimeMillis(); System.out.println("方法" + method.getName() + "耗时:" + (end - start) + "ms"); return obj; } }
测试类Test.java
package wen.hui.proxy; import java.lang.reflect.Proxy; public class Test { public static void main(String[] args) throws IllegalArgumentException, InstantiationException, IllegalAccessException { MyServiceImpl service = new MyServiceImpl(); MyHandler handler = new MyHandler(service); MyService proxy = (MyService)Proxy.newProxyInstance(service.getClass().getClassLoader(),service.getClass().getInterfaces(), handler); proxy.add(); proxy.remove(); } }
运行结果:
add success... 方法add耗时:110ms remove success... 方法remove耗时:109ms