Configuring Transactions in XML with Spring
by, 11-27-2011 at 11:33 PM (3593 Views)
Continuing from my previous post, I will demonstrate how you can declare transactions in XML using Spring. Continuing from the previous tips on transaction attributes, letís dive straight in. Spring has a tx configuration namespace to simply declaring transactions in Spring. It is recommended that you include the aop namespace as well since some of the declarative transaction configuration elements use AOP configuration elements. The following shows how <tx:advice> is used for the Car service.
Note that the transaction attributes are defined using the <tx:attributes> element. It contains one or more <tx:method> elements depending on the level of granularity that you need to use for the methods defined for the service. The <tx:method> element defines the transaction attributes for the given method(s) defined by the name attribute(s). I list the attributes that define transactions policies below:Java Code:<tx:advice id="txAdvice"> <tx:attributes> <tx:method name="prepare*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice>
So in terms of the CarService we have the prepareCar and the addCar that requires a transaction and the other methods will run in a transaction if one exists, but donít need a transaction. Remember that you need a transaction manager. The straightforward manner to do this is to declare the transaction manager as a bean. You can then specify the transaction manager in the <tx:advice>:
To turn this into a complete transactional aspect, it is necessary to define an advisor. The way to do this is to use a pointcut attribute to indicate this advisor advises all methods of the CarService interface. I give you an example of this below:Java Code:<tx:advice id="txAdvice" transaction-manager="txManager"> ... </tx:advice>
In a future tip, I will give you a tip for defining annotation-driven transactions.Java Code:<aop:config> <aop:advisor pointcut="execution(* *..CarService.*(..))" advice-ref="txAdvice"/> </aop:config>