Suppose we have following class
@Service
class MyClass {
public void testA() {
testB();
}
@Transactional
public void testB() { ... }
}
Now, if we invoke myClass.testA(); in test, then @Transactional on testB will not take effect. The reason I think is following.
Cglib will create a proxy bean for MyClass, like this:
Class Cglib$MyClass extends MyClass {
@Override
public void testB() {
// ...do transactional things
super.testB();
}
}
Now we invoke myClass.testA(), which will invoke MyClass.testB() instead of Cglib$MyClass.testB(). So @Transactional is not effective. (Am I right?)
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();
}
}
In this case, although we successfully invoke Cglib$MyClass.testA(), it will still goes to MyClass.testB().
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!