可能已经晚了,但我遇到了一些东西,它很好地解释了您对代理的担忧(只有通过代理传入的“外部”方法调用才会被拦截)。
例如,您有一个看起来像这样的类
@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;
// getter/setters
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();
//subordinate.doSomethingSmall(4);
}
你看,这个方法在内部调用了另一个方法,所以它不会被拦截,输出看起来像这样:
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");
//doSomethingSmall(4);
((CoreBusinessSubordinate) AopContext.currentProxy()).doSomethingSmall(4);
}
代码片段取自:
https ://www.intertech.com/Blog/secrets-of-the-spring-aop-proxy/