Junior — Middle
How to determine the number of transactions when calling a method annotated with @Transactional from another method with the same annotation in a different class in Spring?
sobes.tech AI
Answer from AI
In Spring, the @Transactional annotation manages transactions at the proxy level. When calling a method annotated with @Transactional from another class also annotated with @Transactional, Spring creates or uses an existing transaction depending on the propagation settings.
To determine the number of transactions in such a call, consider:
- Propagation (transaction propagation behavior): by default,
REQUIRED— if a transaction already exists, the method will run within it; a new one is not created. - Call from another class: Spring proxy triggers, and transaction management occurs correctly.
For precise counting of transactions, you can use:
- Logging or debugging the transaction manager.
- Injecting a custom
PlatformTransactionManageror transaction listener. - Using AOP to intercept transaction start and end.
Example of logging transaction start:
@Component
public class TransactionLogger implements TransactionSynchronization {
@Override
public void beforeCommit(boolean readOnly) {
System.out.println("Transaction begins");
}
@Override
public void afterCompletion(int status) {
System.out.println("Transaction completed");
}
}
And registering this listener in TransactionSynchronizationManager.
Thus, when calling a method with @Transactional from another class with @Transactional, usually only one transaction will be active unless propagation is changed.