View RSS Feed

Spring Framework

Using Annotations for Transactions in Spring

Rate this Entry
by , 11-27-2011 at 11:38 PM (3187 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 :

Java Code:
<tx:annotation-driven transaction-manager="txManager" />
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:
@Transactional(propagation=Propagation.SUPPORTS, readOnly=true) 
public class CarServiceImpl implements CarService { 
...
     @Transactional(propagation=Propagation.REQUIRED, readOnly=false)
     public void prepareCare(Car car) { 
...
     } 
...
}
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!

Submit "Using Annotations for Transactions in Spring" to Facebook Submit "Using Annotations for Transactions in Spring" to Digg Submit "Using Annotations for Transactions in Spring" to del.icio.us Submit "Using Annotations for Transactions in Spring" to StumbleUpon Submit "Using Annotations for Transactions in Spring" to Google

Comments