Using Annotations for Transactions in Spring
by , 11-27-2011 at 10:38 PM (1949 Views)
In the previous tip, I showed you how you could use XML to define a transaction. In this tip we will look at doing the same using annotations. It is blindly simple to use annotations for transactions. The tx namespace provides the <tx:annotation-driven> element. It appears like this :
With this you can now define transaction rules very easily. This tag tells Spring to examine all beans in the application context and look for the ones annotate with @Transaction. This can be at the class or method level. For each one that it finds, it will automatically advise it transactional advice. The transactional attributes of advice will be defined by parameters of the @Transactional annotation.Java Code:<tx:annotation-driven transaction-manager="txManager" />
In this case, CarServiceImpl has been annotated at the class level with the @Transactional annotation. This means that all methods will support transaction and be read-only. Further at the method level, the prepareCar() method has been annotated to indicate that this method requires a transactional context. That’s all. Until next time!Java Code:@Transactional(propagation=Propagation.SUPPORTS, readOnly=true) public class CarServiceImpl implements CarService { ... @Transactional(propagation=Propagation.REQUIRED, readOnly=false) public void prepareCare(Car car) { ... } ... }









Email Blog Entry
License4J 4.0
Yesterday, 12:23 AM in Java Software