日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

做一些Spring AOP做过的事,封装 jdk动态代理成为一个黑盒子

發布時間:2025/4/5 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 做一些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动态代理成为一个黑盒子的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。