Spring入門學習(基於XML檔案的方式配置事務) 第二十一節
阿新 • • 發佈:2019-01-12
Spring入門學習(基於XML檔案的方式配置事務)
XML方式配置事務
- 複製之前的包,去掉相關的註解,新建Spring配置檔案如下:
測試方法如下:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
此時設定餘額為30,兩本書的庫存為10本,執行public class SpringTransactionTest { private ApplicationContext ctx = null; private BookShopDao bookShopDao = null; private BookShopService bookShopService = null; private Cashier cashier = null; { ctx = new ClassPathXmlApplicationContext("classpath:applicationContext-tx-xml.xml"); bookShopDao = ctx.getBean(BookShopDao.class); bookShopService = ctx.getBean(BookShopService.class); cashier = ctx.getBean(Cashier.class); } @Test public void testBookShopService() { bookShopService.purchase("AA", "1001"); } @Test public void testTansactionPropagation() { cashier.checkout("AA", Arrays.asList("1001","1002")); } }
testBookShopService
後由於目前還沒有事務控制,所以提示餘額不足後,1001的庫存仍然會減1。
- 新增事務管理
再次執行<!-- 1.配置事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 2.配置事務屬性(隔離級別,只讀) --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 3.配置事務切入點及把事務切入點和事務屬性關聯起來 --> <aop:config> <aop:pointcut expression="execution(* com.fafa.spring.tx.xml.BookShopService.*(..))" id="txPointCut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config>
testBookShopService
方法後,由於事務管理,所以當餘額不足時,事務會發生回滾,庫存不變。 - 修改包結構如下(記得修改xml檔案中引入的包名):
事務的切點可以修改如下:<!-- 3.配置事務切入點及把事務切入點和事務屬性關聯起來 --> <aop:config> <aop:pointcut expression="execution(* com.fafa.spring.tx.xml.service.*.*(..))" id="txPointCut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config>
- 測試
修改餘額為300,庫存都為10,執行testTansactionPropagation
方法購買兩本書:
購買成功,餘額-170,庫存各自-1。
- 我們再測試事務的傳播屬性,為
purchase
方法新增屬性,修改配置如下:
測試再來測試<!-- 2.配置事務屬性(隔離級別,只讀) --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 根據方法名指定事務的屬性 --> <tx:method name="purchase" propagation="REQUIRES_NEW"/> <tx:method name="get*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice>
testTansactionPropagation
方法:
結果為餘額不變,1001的庫存-1。