M03 Q15 What happens if one @Transactional annotated method is calling another @Transactional annotated method on the same object instance?
JDK Proxy and CGLIB Proxy in Spring Beans AOP do not support self-invocation, so when one method with @Transactional annotation calls different method with @Transactional annotation from the same class, nothing happens, transaction interceptor will not be called.
How it works with spring-proxy?
When transaction1And2() is started nothing will be happend with connection, because transaction1And2() method is not annotated with @Transactional annotation. Then transaction1And2() call transaction1() and transaction2() method which are annotated with @Transactional annotation. But transactions will not be created for those methods.
Anther example transaction1And2WithPrecedingTransaction() method which is annotated with @Transactional will get the connection and create the transaction. When transaction1() and transaction2() will be called from that method nothing will happen. After transaction1And2WithPrecedingTransaction() method finished connection will be committed and closed.
Spring AspectJ Support
To enable self-invocation support, you need to configure Spring Aspects with AspectJ, to do that you need to:
- Have dependency to
spring-aspects - Include
aspectj-maven-plugin - Configure Transaction Support with
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)