簡單學習 AOP實現原理

2021-10-11 01:39:23 字數 2182 閱讀 7549

spring裡最重要的兩個特性就當屬ioc和aop吧,對於aop的原理最近看書自我感覺理解了不少,在此還是做個筆記記錄一下,不要只有嘴上功夫。

直接通過乙個例子來說明吧,本人組織能力不太行,從別人那複製貼上過來也沒啥意思,懂的都懂,感覺沒啥必要哈哈哈哈哈哈哈哈

先建立乙個簡單的介面和它的實現類

//使用的是jdk自帶的方法生成**物件實現切面的效果,因此介面是不能少的,不用介面的那個cglib,那個以後看看吧

public

inte***ce

helloservice

public

class

helloserviceimpl

implements

helloservice

system.out.

println

("hello "

+name);}

}

定義invocation類,它用是於實現環繞通知功能的乙個類,主要就是通過反射進行作用

public

class

invocation

//getset方法省略

}

定義***介面以及實現類

public

inte***ce

interpector

public

class

myinterceptor

implements

interpector

@override

public

void

after()

@override

public object around

(invocation invocation)

throws invocationtargetexception, illegalacces***ception

@override

public

void

afterreturning()

@override

public

void

afterthrowing()

@override

public

boolean

usearound()

}

生成**物件的工具類

//注意這個實現了jdk自帶的invocationhandler介面

public

class

proxycreator

implements

invocationhandler

else

}catch

(exception e)

interceptor.

after()

;if(exceptionflag)

else

return null;

}public

static object getproxybean

(object target, interceptor interceptor)

}

簡單寫乙個測試類測試一下

public

class

aoptest

@test

public

void

test_name_is_not_null()

@test

public

void

test_name_is_null()

}

結果如下

#test_name_is_not_null

before..............

around before.......

hello world

around after........

after...............

after returning.....

#test_name_is_null

before..............

around before.......

after...............

after throwing......

aop的實現原理

aop涉及 動態 和反射 不懂可以上網查查資料 大概實現原理就是 介面itest 裡面有方法 public void test 具體實現類 test implements itest 個人理解,動態 就是通過反射從實現類test中提取了方法test 的所有資訊,然後jvm通過一些dll什麼的重新寫了...

探秘AOP實現原理

可以這麼說,aop是基於動態 實現的。那麼,這個過程是怎樣的?首先,我們有這樣的乙個service類,它是被作為切面的乙個類 public class service implements user new handler new service 這裡需要實現乙個handler public cla...

簡單AOP實現過程

切面類實現 aspect public class logaspects before在目標方法之前切入 切入點表示式 指定在哪個方法切入 before pointcut public void logstart joinpoint joinpoint after com.atguigu.aop.l...