call捕获的joinpoint是调用方法的地方,execution捕获的joinpoint是执行的地方
验证execution
HelloAspect.aj
package aspectj;
public aspect HelloAspect {
pointcut HelloWorldPointCut() : execution(* aspectj.HelloWorld.main(int));
before() : HelloWorldPointCut() {
System.out.println("拦截位置"+thisJoinPoint.getSourceLocation());
}
}
image.png
输出:
main
拦截位置HelloWorld.java:11
i=5
验证call
直接修改HelloAspect.aj这个aspect的pointcut为call
输出:
main
拦截位置HelloWorld.java:8
i=5
within
新建Student类和Teacher类
image.png
HelloWorld.java
package aspectj;
public class HelloWorld {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("main");
Teacher teacher=new Teacher();
teacher.print();
Student student=new Student();
student.print();
}
}
HelloAspet.aj
package aspectj;
public aspect HelloAspect {
pointcut PrintPointCut() : execution(* print(..));
before() : PrintPointCut() {
System.out.println("拦截位置"+thisJoinPoint.getSourceLocation());
}
}
Student.java
package aspectj;
public class Student {
public void print()
{
System.out.println("student");
}
}
Teacher.java
package aspectj;
public class Teacher {
public void print()
{
System.out.println("Teacher");
}
}
运行结果:
main
拦截位置Teacher.java:5
Teacher
拦截位置Student.java:7
student
image.png
image.png
image.png
image.png
如果现在有个需求,只想拦截Teacher类中的print方法,其余的类不拦截(这里只演示了一个Student类,假设有很多类都有print方法该怎么实现呢?)
修改程序的pointcut
package aspectj;
public aspect HelloAspect {
pointcut PrintPointCut() : execution(* print(..))&&within(Teacher);
before() : PrintPointCut() {
System.out.println("拦截位置"+thisJoinPoint.getSourceLocation());
}
}
输出结果:
main
拦截位置Teacher.java:5
Teacher
student
withincode
相对于within来说,这个pointcut是针对类内部进行拦截的,看个示例就清楚了
修改
Teacher.java
package aspectj;
public class Teacher {
public void print()
{
System.out.println("Teacher");
}
public void callPrintfirst()
{
print();
}
public void callPrintSecond()
{
print();
}
public void callPrintThree()
{
print();
}
}
Teacher中有三个方法都调用了print()方法,但是现在只想要拦截callPrintfirst()方法调用的print方法,其余的不拦截
HelloWorld.java
package aspectj;
public class HelloWorld {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("main");
Teacher teacher=new Teacher();
teacher.callPrintfirst();
teacher.callPrintSecond();
teacher.callPrintThree();
}
}
HelloAspect.aj
package aspectj;
public aspect HelloAspect {
pointcut PrintPointCut() : call(* print(..))&&withincode(* aspectj.Teacher.callPrintfirst(..));
before() : PrintPointCut() {
System.out.println("拦截位置"+thisJoinPoint.getSourceLocation());
}
}
运行代码,输出结果:
main
拦截位置Teacher.java:11
Teacher
Teacher
Teacher
image.png