call捕獲的joinpoint是調用方法的地方,execution捕獲的joinpoint是執(zhí)行的地方
驗證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
如果現(xiàn)在有個需求,只想攔截Teacher類中的print方法,其余的類不攔截(這里只演示了一個Student類,假設有很多類都有print方法該怎么實現(xiàn)呢?)
修改程序的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()方法,但是現(xiàn)在只想要攔截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