1.配置普通的 controller,service ,dao 的bean.
<!-- 配置 dao ,service --> <bean id="bookShopDao" class="com.liujl.spring.tx.xml.BookShopDaoImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"></property> </bean> <bean id="bookShopService" class="com.liujl.spring.tx.xml.serivice.impl.BookShopServiceImpl"> <property name="bookShopDao" ref="bookShopDao"></property> </bean> <bean id="cashier" class="com.liujl.spring.tx.xml.serivice.impl.CashierImpl"> <property name="bookShopService" ref="bookShopService"></property> </bean>
2.配置事務(wù)管理器bean
<!-- 配置事務(wù)管理器 hibernate、jpa都是類似的這樣配 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean>
3.引入 tx 命名空間
xmlns:tx="http://www.springframework.org/schema/tx"
4.配置事務(wù)各個屬性(方法名可以使用通配符*)
<!-- 配置事務(wù)屬性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="purchase" propagation="REQUIRED"/> <tx:method name="checkout" propagation="REQUIRED"/> <tx:method name="get*" read-only="true"/> <tx:method name="find*" read-only="true"/> </tx:attributes> </tx:advice>
5.引入aop命名空間
xmlns:aop="http://www.springframework.org/schema/aop"
6.配置事務(wù)的切點,并把事務(wù)切點和事務(wù)屬性關(guān)聯(lián)起來
<!-- 配置事務(wù)的切點,并把事務(wù)切點和事務(wù)屬性不關(guān)聯(lián)起來 --> <aop:config> <aop:pointcut expression="execution(* com.liujl.spring.tx.xml.serivice.*.*(..))" id="txPointCut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config>
事務(wù)的屬性:
1.使用 propagation 聲明事務(wù)的傳播屬性,默認即 REQUIRED 即被包含在上面的事務(wù)中,放棄自己處理事務(wù) REQUIRES_NEW 以本方法為執(zhí)行單位,開啟一個新事務(wù)(外部事務(wù)在方法執(zhí)行前后被掛起) 2.使用 isolation 指定事務(wù)的隔離級別,最常用的取值為 READ_COMMITTED 讀與提交
3.默認情況下Spring 的聲明式事務(wù)對所有的運行時一樣長進行回滾。 也可以對應(yīng)的屬性指定配置,通常情況下取默認值即可。使用 noRollbackFor 指定不回滾的異常,其他的類似
4.使用 readOnly 指定事務(wù)是否為只讀,表示這個事務(wù)只讀取數(shù)據(jù)但不更新數(shù)據(jù), 這樣可以幫助數(shù)據(jù)庫引擎優(yōu)化事務(wù)。若真的是一個只讀取數(shù)據(jù)庫值得方法,應(yīng)設(shè)置readOnly=true
5.使用 timeout 指定強制回滾之前事務(wù)可以占用的時間
新聞熱點
疑難解答