Spring has a great way to handle transactions using @Transactional
annotation. However, there are a few gotchas that one needs to watch out for. Without a good understanding of how Spring treats transactions, you can run into some unexpected and undesirable behavior. For an in depth study of the topic refer to the Spring Documentation on transaction management. I will try to summarize a few important points.
1. Spring provides support for transactions using AOP Proxies
It means that you are not calling a method directly but through a proxy. This is a very important point to remember when defining transaction boundaries. In an event where a service method calls another method in the same class with a different propagation setting (PROPAGATION_REQUIRES_NEW
for example), that setting will be ignored since the call is made internally. If you are not aware of the AOP concept the behavior of those methods will most likely not match your expectations.
In order to let Spring manage transactions you have to add @EnableTransactionManagement
to your Java config class or if using XML configuration add
<tx:annotation-driven/> . (Don’t forget the namespace:
xmlns:tx="http://www.springframework.org/schema/tx"