log()是系统日志,可以利用切面编程将他模块化,热插拔的插入到invoke方法周围
针对之前的代码,应该抽取黄色部分出来,并模块化
目标抽取成为一个参数
final ArrayList target=new ArrayList(); Collection proxy3 = (Collection) getProxy(target,new MyAdvice());
系统功能抽取成一个对象
public static Object getProxy(final Object target,final Advice advice) { Object proxy3 = Proxy.newProxyInstance( Collection.class.getClassLoader(), new Class[]{Collection.class}, new InvocationHandler(){ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { advice.beforeMethod(method); Object reVal=method.invoke(target, args); advice.afterMethod(method); return reVal; } } ); return proxy3; }
通知接口--契约
package com.itcast.day3; import java.lang.reflect.Method; public interface Advice { public void beforeMethod(Method method); public void afterMethod(Method method); }
契约的实现--通常是上班时使用Spring aop 时,工作量最大的工作
package com.itcast.day3; import java.lang.reflect.Method; public class MyAdvice implements Advice { long beginTime=0; @Override public void beforeMethod(Method method) { beginTime=System.currentTimeMillis(); } @Override public void afterMethod(Method method) { long endTime=System.currentTimeMillis(); System.out.println(method.getName()+" running "+(endTime-beginTime)); } }
使用spring的aop时,只需干两件事
1 配置Advice
2 配置 target