同一类调用在Spring AOP cglib中无效 [英] Same class invoke NOT effective in Spring AOP cglib
问题描述
假设我们有以下课程
@Service
class MyClass {
public void testA() {
testB();
}
@Transactional
public void testB() { ... }
}
现在,如果我们在测试中调用myClass.testA();
,则testB
上的@Transactional
将不会生效.我认为原因如下.
Now, if we invoke myClass.testA();
in test, then @Transactional
on testB
will not take effect. The reason I think is following.
Cglib将为MyClass
创建一个代理bean,如下所示:
Cglib will create a proxy bean for MyClass
, like this:
Class Cglib$MyClass extends MyClass {
@Override
public void testB() {
// ...do transactional things
super.testB();
}
}
现在,我们调用myClass.testA()
,它将调用MyClass.testB()
而不是Cglib$MyClass.testB()
.因此@Transactional
无效. (我说得对吗?)
Now we invoke myClass.testA()
, which will invoke MyClass.testB()
instead of Cglib$MyClass.testB()
. So @Transactional
is not effective. (Am I right?)
我尝试为两种方法(即testA()
和testB()
)添加@Transactional
.代理类应该这样.
I tried to add @Transactional
for both methods (i.e. testA()
and testB()
). The proxy class should like this.
Class Cglib$MyClass extends MyClass {
@Override
public void testA() {
// ...do transactional things
super.testA();
}
@Override
public void testB() {
// ...do transactional things
super.testB();
}
}
在这种情况下,尽管我们成功调用了Cglib$MyClass.testA()
,它仍将转到MyClass.testB()
.
In this case, although we successfully invoke Cglib$MyClass.testA()
, it will still goes to MyClass.testB()
.
所以我的结论是,除非我们使用AopContext.currentProxy()
,否则同一类中的两个方法相互调用将使aop注释无法生效.
So my conclusion is, two methods in same class invoking each other will make aop annotation fail to take effect, unless we use AopContext.currentProxy()
.
我猜对了吗?非常感谢您的建议!
Am I right on above guess? Thanks very much for advice!
推荐答案
这是众所周知的this.someMethod(..).
It is a well-known and documented (please search for the term "self-invocation") fact that Spring AOP, due to its proxy-based nature, does not and cannot capture internal method calls like this.someMethod(..)
.
因此,正如您所说,您需要显式引用公开的代理对象,或者从Spring AOP切换到完整的
So as you said, you either need to explicitly refer to the exposed proxy object or alternatively switch from Spring AOP to full AspectJ via load-time weaving.
这篇关于同一类调用在Spring AOP cglib中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!