aspect java是一個面向切面的框架,它擴展了Java語言。AspectJ定義了AOP語法所以它有一個專門的編譯器用來生成遵守Java字節編碼規范的Class文件。
首先是幾個概念:
aspect(層面)
pointcut(切入點)
advice(建議)
weave(織入)
LTW(加載期織入 load time weave)
按照aspectj的語法規則,一個aspect就是很多pointcut和advice的集合,也就是一個*.aj的文件。
一個pointcut就是對target class的切入點定義,類似Java class定義中的field。
一個advice就是對target class的行為改變,類似Java class中的method。
weave就是aspectj runtime庫把aspect織入到target class的行為。
LTW就是指運行期間動態織入aspect的行為,它是相對靜態織入行為(包括對源文件、二進制文件的修改)。
一般來講,從運行速度上來說,靜態織入比動態織入要快些。因為LTW需要使用aspectj本身的classloader,它的效率要低于jdk的classloader,因此當需要load的class非常多時,就會很慢的。
舉個例子來說明aspectj的使用:
scenario: Example工程需要使用一個類Line存在于第三方庫Line.jar中,但是Line本身沒有實現Serializable接口,并且其toString方法輸出也不完善。因此這兩點都需要修改。
Line的實現:
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)
以上就是小編今天的分享了,希望可以幫助到大家。