虽然来得有些晚,但我找到了一些能够很好地解释你关于代理的疑惑(只有通过代理进行的“外部”方法调用才会被拦截)。
例如,你有一个长这样的类:
@Component("mySubordinate")
public class CoreBusinessSubordinate {
public void doSomethingBig() {
System.out.println("I did something small");
}
public void doSomethingSmall(int x){
System.out.println("I also do something small but with an int");
}
}
你有一个类似于这样的方面:
@Component
@Aspect
public class CrossCuttingConcern {
@Before("execution(* com.intertech.CoreBusinessSubordinate.*(..))")
public void doCrossCutStuff(){
System.out.println("Doing the cross cutting concern now");
}
}
当您像这样执行它时:
@Service
public class CoreBusinessKickOff {
@Autowired
CoreBusinessSubordinate subordinate;
public void kickOff() {
System.out.println("I do something big");
subordinate.doSomethingBig();
subordinate.doSomethingSmall(4);
}
调用以上给定代码的kickOff函数的结果如下:
I do something big
Doing the cross cutting concern now
I did something small
Doing the cross cutting concern now
I also do something small but with an int
但是当您更改代码为
@Component("mySubordinate")
public class CoreBusinessSubordinate {
public void doSomethingBig() {
System.out.println("I did something small");
doSomethingSmall(4);
}
public void doSomethingSmall(int x){
System.out.println("I also do something small but with an int");
}
}
public void kickOff() {
System.out.println("I do something big");
subordinate.doSomethingBig();
}
您可以看到,该方法内部调用了另一个方法,因此它不会被拦截,输出如下:
I do something big
Doing the cross cutting concern now
I did something small
I also do something small but with an int
您可以通过这种方式绕过此问题
public void doSomethingBig() {
System.out.println("I did something small");
((CoreBusinessSubordinate) AopContext.currentProxy()).doSomethingSmall(4);
}
代码片段来源:
https://www.intertech.com/Blog/secrets-of-the-spring-aop-proxy/
该页面已不存在。