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)以上就是小编今天的分享了,希望可以帮助到大家。