javascript
做一些Spring AOP做过的事,封装 jdk动态代理成为一个黑盒子
?
怎么使用eclise 抽取方法,請看? 利用eclipse 抽取代碼片段為方法
?
抽取完成之后,還需要
① 將Collection.class換成? target.getClass(),target是Object的,可以來代理所有的對象
② Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHander(){
??? invoke(Object proxy,Method method,Object[] args) {
???????????? advice.beforeMethod(method);//我們在使用Spring AOP時,只寫 beforeMethod類似的交叉功能的實現
??????????? Object? retVal=? proxy.invoke(target,args);
??????????? advice.afterMethod(method);//我們在使用Spring AOP時,只寫 afterMethod 類似的交叉功能方法的實現
???????????? return? retVal;
}
}
)
?
?
我通過eclipse封裝好的黑匣子
private static Object getProxy(final Object target,final Advice advice) {Object proxy3=(Collection)Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {/* long beginTime=System.currentTimeMillis();Object retVal=method.invoke(target, args);long endTime=System.currentTimeMillis();System.out.println(method.getName()+"執行時間 "+(endTime-beginTime)+" 毫秒");return retVal;*/advice.beforeMethod(method);Object retVal=method.invoke(target, args);advice.afterMethod(method);return retVal;}});return proxy3;}?
?
這么調用黑匣子
final ArrayList target=new ArrayList();//類變量Collection proxy3 = (Collection) getProxy(target,new MyAdvice());?
?
我寫的MyAdvice,其中Advice將來由Spring定義好,里面會有各種位置的方法,如afterMethod,beforeMethod, after throwing? , around
package com.itcast.day3;import java.lang.reflect.Method;public class MyAdvice implements Advice {long beginTime=0;@Overridepublic void beforeMethod(Method method) {System.out.println("到傳智播客學習啦...");beginTime=System.currentTimeMillis();}@Overridepublic void afterMethod(Method method) {System.out.println("從傳智播客畢業工作啦...");long endTime=System.currentTimeMillis();System.out.println(method.getName()+"執行時間 "+(endTime-beginTime)+" 毫秒");}}?
將來使用Spring? AOP時,只做兩件事,
① 確定目標對象target
② 寫MyAdvice (其實就是實現Spring 提供的Advice接口中的? beforeMethod, afterMethod方法)
開始做,堅持做,重復做總結
以上是生活随笔為你收集整理的做一些Spring AOP做过的事,封装 jdk动态代理成为一个黑盒子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JS 获取中英字符串字节长度
- 下一篇: OneZero第四周第四次站立会议(20