aspect java是一個(gè)面向切面的框架,它擴(kuò)展了Java語(yǔ)言。AspectJ定義了AOP語(yǔ)法所以它有一個(gè)專門的編譯器用來(lái)生成遵守Java字節(jié)編碼規(guī)范的Class文件。
首先是幾個(gè)概念:
aspect(層面)
pointcut(切入點(diǎn))
advice(建議)
weave(織入)
LTW(加載期織入 load time weave)
按照aspectj的語(yǔ)法規(guī)則,一個(gè)aspect就是很多pointcut和advice的集合,也就是一個(gè)*.aj的文件。
一個(gè)pointcut就是對(duì)target class的切入點(diǎn)定義,類似Java class定義中的field。
一個(gè)advice就是對(duì)target class的行為改變,類似Java class中的method。
weave就是aspectj runtime庫(kù)把a(bǔ)spect織入到target class的行為。
LTW就是指運(yùn)行期間動(dòng)態(tài)織入aspect的行為,它是相對(duì)靜態(tài)織入行為(包括對(duì)源文件、二進(jìn)制文件的修改)。
一般來(lái)講,從運(yùn)行速度上來(lái)說(shuō),靜態(tài)織入比動(dòng)態(tài)織入要快些。因?yàn)長(zhǎng)TW需要使用aspectj本身的classloader,它的效率要低于jdk的classloader,因此當(dāng)需要load的class非常多時(shí),就會(huì)很慢的。
舉個(gè)例子來(lái)說(shuō)明aspectj的使用:
scenario: Example工程需要使用一個(gè)類Line存在于第三方庫(kù)Line.jar中,但是Line本身沒(méi)有實(shí)現(xiàn)Serializable接口,并且其toString方法輸出也不完善。因此這兩點(diǎn)都需要修改。
Line的實(shí)現(xiàn):
package?bean; public?class?Line?{undefined protected?int?x1?=?0; protected int?x2?=?0; public?int getX1(){undefined return?x1; } public?int getX2(){undefined return?x2; } public?void setLength(int?newX,?int?newY){undefined setX1(newX); setX2(newY); } public?void setX1(int?newX)?{undefined x1?=?newX; } public?void setX2(int?newY)?{undefined x2?=?newY; } public String?toString(){undefined return?"("?+?getX1()?+?",?"?+?getX2()?+?")"?; } } Main?entry?: public?class?MyExample?{undefined private?Line?line?=?null; public?MyExample()?{undefined line?=?new?Line(); System.err.println("Line implement?serializable?interface?:?" + (line?instanceof?Serializable)); } public?void?showMe()?{undefined System.out.println("Show?all about?me?..."); System.out.println(line.toString()); } public?static?void?main(String[]?args)?{undefined MyExample?demo?=?new MyExample(); //?i?want?to?change?the?action of?show?me,?but?i?cannot?get?line?source. //?so?i?will?trying?load-time weaving demo.showMe(); } } output?: Line?implement?serializable?interface?:?true Show?all?about?me?... (0,?0)
以上就是小編今天的分享了,希望可以幫助到大家。