
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
新聞熱點
疑難解答