Spring編程式和聲明式事務(wù)實(shí)例講解小結(jié)
Spring事務(wù)管理
Spring支持兩種方式的事務(wù)管理:
- 編程式事務(wù)管理: 通過Transaction Template手動管理事務(wù),實(shí)際應(yīng)用中很少使用,
- 使用XML配置聲明式事務(wù): 推薦使用(代碼侵入性最?。?,實(shí)際是通過AOP實(shí)現(xiàn)
實(shí)現(xiàn)聲明式事務(wù)的四種方式:
- 基于 TransactionInterceptor 的聲明式事務(wù): Spring 聲明式事務(wù)的基礎(chǔ),通常也不建議使用這種方式,但是與前面一樣,了解這種方式對理解 Spring 聲明式事務(wù)有很大作用。
- 基于 TransactionProxyFactoryBean 的聲明式事務(wù): 第一種方式的改進(jìn)版本,簡化的配置文件的書寫,這是 Spring 早期推薦的聲明式事務(wù)管理方式,但是在 Spring 2.0 中已經(jīng)不推薦了。
- 基于< tx> 和< aop>命名空間的聲明式事務(wù)管理: 目前推薦的方式,其最大特點(diǎn)是與 Spring AOP 結(jié)合緊密,可以充分利用切點(diǎn)表達(dá)式的強(qiáng)大支持,使得管理事務(wù)更加靈活。
- 基于 @Transactional 的全注解方式: 將聲明式事務(wù)管理簡化到了極致。開發(fā)人員只需在配置文件中加上一行啟用相關(guān)后處理 Bean 的配置,然后在需要實(shí)施事務(wù)管理的方法或者類上使用 @Transactional 指定事務(wù)規(guī)則即可實(shí)現(xiàn)事務(wù)管理,而且功能也不必其他方式遜色。
我們今天要將的是使用編程式以及基于AspectJ的聲明式和基于注解的事務(wù)方式,實(shí)現(xiàn)爛大街的轉(zhuǎn)賬業(yè)務(wù)。
再來說一下這個案例的思想吧,我們在兩次轉(zhuǎn)賬之間添加一個錯誤語句(對應(yīng)銀行斷電等意外情況),如果這個時候兩次轉(zhuǎn)賬不能成功,則說明事務(wù)配置正確,否則,事務(wù)配置不正確。
你需要完成的任務(wù):
- 使用編程式事務(wù)管理完成轉(zhuǎn)賬業(yè)務(wù)
- 使用基于AspectJ的聲明式事務(wù)管理完成轉(zhuǎn)賬業(yè)務(wù)
- 使用基于 @Transactional 的全注解方式事務(wù)管理完成轉(zhuǎn)賬業(yè)務(wù)
備注:
下面的代碼是在很久之前,我剛學(xué)Sping還沒有接觸Maven的時候?qū)懙?,所以我使用的原始添加jar的方式,使用Maven的小伙伴可以自行添加Maven依賴
項(xiàng)目結(jié)構(gòu):
Spring編程式和聲明式事務(wù)實(shí)例講解

開發(fā)工具:
Myeclipse2017
SQL:
create table `account` (
`username` varchar (99),
`salary` int (11)
);
insert into `account` (`username`, `salary`) values('小王','3000');
insert into `account` (`username`, `salary`) values('小馬','3000');
(1)編程式事務(wù)管理
注意: 通過添加/刪除accountMoney() 方法中int i = 10 / 0這個語句便可驗(yàn)證事務(wù)管理是否配置正確。
OrdersDao.java(Dao層)
package cn.itcast.dao;
import org.springframework.jdbc.core.JdbcTemplate;
public class OrdersDao {
// 注入jdbcTemplate模板對象
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
// 對數(shù)據(jù)操作的方法不包含業(yè)務(wù)操作
/**
* 小王少錢的方法
*/
public void reduceMoney() {
String sql = "update account set salary=salary-? where username=?";
jdbcTemplate.update(sql, 1000, "小王");
}
/**
* 小馬多錢的方法
*/
public void addMoney() {
String sql = "update account set salary=salary+? where username=?";
jdbcTemplate.update(sql, 1000, "小馬");
}
}
OrdersService.java(業(yè)務(wù)邏輯層)
package cn.itcast.service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import cn.itcast.dao.OrdersDao;
public class OrdersService {
// 注入Dao層對象
private OrdersDao ordersDao;
public void setOrdersDao(OrdersDao ordersDao) {
this.ordersDao = ordersDao;
}
// 注入TransactionTemplate對象
private TransactionTemplate transactionTemplate;
public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
this.transactionTemplate = transactionTemplate;
}
// 調(diào)用dao的方法
// 業(yè)務(wù)邏輯,寫轉(zhuǎn)賬業(yè)務(wù)
public void accountMoney() {
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
Object result = null;
try {
// 小馬多1000
ordersDao.addMoney();
// 加入出現(xiàn)異常如下面int
// i=10/0(銀行中可能為突然停電等。。。);結(jié)果:小馬賬戶多了1000而小王賬戶沒有少錢
// 解決辦法是出現(xiàn)異常后進(jìn)行事務(wù)回滾
int i = 10 / 0;// 事務(wù)管理配置后異常已經(jīng)解決
// 小王 少1000
ordersDao.reduceMoney();
} catch (Exception e) {
status.setRollbackOnly();
result = false;
System.out.println("Transfer Error!");
}
return result;
}
});
}
}
TestService.java(測試方法)
package cn.itcast.service;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestService {
@Test
public void testAdd() {
ApplicationContext context = new ClassPathXmlApplicationContext(
"beans.xml");
OrdersService userService = (OrdersService) context
.getBean("ordersService");
userService.accountMoney();
}
}
配置文件:
<?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 配置c3po連接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 注入屬性值 --> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/wangyiyun"></property> <property name="user" value="root"></property> <property name="password" value="153963"></property> </bean> <!-- 編程式事務(wù)管理 --> <!-- 配置事務(wù)管理器 --> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入dataSource --> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事務(wù)管理器模板 --> <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate"> <!-- 注入真正進(jìn)行事務(wù)管理的事務(wù)管理器,name必須為 transactionManager否則無法注入 --> <property name="transactionManager" ref="dataSourceTransactionManager"></property> </bean> <!-- 對象生成及屬性注入 --> <bean id="ordersService" class="cn.itcast.service.OrdersService"> <property name="ordersDao" ref="ordersDao"></property> <!-- 注入事務(wù)管理的模板 --> <property name="transactionTemplate" ref="transactionTemplate"></property> </bean> <bean id="ordersDao" class="cn.itcast.dao.OrdersDao"> <property name="jdbcTemplate" ref="jdbcTemplate"></property> </bean> <!-- JDBC模板對象 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
(2)基于AspectJ的聲明式事務(wù)管理
OrdersService.java(業(yè)務(wù)邏輯層)
package cn.itcast.service;
import cn.itcast.dao.OrdersDao;
public class OrdersService {
private OrdersDao ordersDao;
public void setOrdersDao(OrdersDao ordersDao) {
this.ordersDao = ordersDao;
}
// 調(diào)用dao的方法
// 業(yè)務(wù)邏輯,寫轉(zhuǎn)賬業(yè)務(wù)
public void accountMoney() {
// 小馬多1000
ordersDao.addMoney();
// 加入出現(xiàn)異常如下面int i=10/0(銀行中可能為突然停電等。。。);結(jié)果:小馬賬戶多了1000而小王賬戶沒有少錢
// 解決辦法是出現(xiàn)異常后進(jìn)行事務(wù)回滾
int i = 10 / 0;// 事務(wù)管理配置后異常已經(jīng)解決
// 小王 少1000
ordersDao.reduceMoney();
}
}
配置文件:
<!-- 配置c3po連接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 注入屬性值 --> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/wangyiyun"></property> <property name="user" value="root"></property> <property name="password" value="153963"></property> </bean> <!-- 第一步:配置事務(wù)管理器 --> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入dataSource --> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 第二步:配置事務(wù)增強(qiáng) --> <tx:advice id="txadvice" transaction-manager="dataSourceTransactionManager"> <!-- 做事務(wù)操作 --> <tx:attributes> <!-- 設(shè)置進(jìn)行事務(wù)操作的方法匹配規(guī)則 --> <!-- account開頭的所有方法 --> <!-- propagation:事務(wù)傳播行為; isolation:事務(wù)隔離級別; read-only:是否只讀; rollback-for:發(fā)生那些異常時回滾 timeout:事務(wù)過期時間 --> <tx:method name="account*" propagation="REQUIRED" isolation="DEFAULT" read-only="false" rollback-for="" timeout="-1" /> </tx:attributes> </tx:advice> <!-- 第三步:配置切面 切面即把增強(qiáng)用在方法的過程 --> <aop:config> <!-- 切入點(diǎn) --> <aop:pointcut expression="execution(* cn.itcast.service.OrdersService.*(..))" id="pointcut1" /> <!-- 切面 --> <aop:advisor advice-ref="txadvice" pointcut-ref="pointcut1" /> </aop:config> <!-- 對象生成及屬性注入 --> <bean id="ordersService" class="cn.itcast.service.OrdersService"> <property name="ordersDao" ref="ordersDao"></property> </bean> <bean id="ordersDao" class="cn.itcast.dao.OrdersDao"> <property name="jdbcTemplate" ref="jdbcTemplate"></property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean>
(3)基于注解的方式
OrdersService.java(業(yè)務(wù)邏輯層)
package cn.itcast.service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.itcast.dao.OrdersDao;
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false, timeout = -1)
public class OrdersService {
private OrdersDao ordersDao;
public void setOrdersDao(OrdersDao ordersDao) {
this.ordersDao = ordersDao;
}
// 調(diào)用dao的方法
// 業(yè)務(wù)邏輯,寫轉(zhuǎn)賬業(yè)務(wù)
public void accountMoney() {
// 小馬多1000
ordersDao.addMoney();
// 加入出現(xiàn)異常如下面int i=10/0(銀行中可能為突然停電等。。。);結(jié)果:小馬賬戶多了1000而小王賬戶沒有少錢
// 解決辦法是出現(xiàn)異常后進(jìn)行事務(wù)回滾
// int i = 10 / 0;// 事務(wù)管理配置后異常已經(jīng)解決
// 小王 少1000
ordersDao.reduceMoney();
}
}
配置文件:
<!-- 配置c3po連接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 注入屬性值 --> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/wangyiyun"></property> <property name="user" value="root"></property> <property name="password" value="153963"></property> </bean> <!-- 第一步:配置事務(wù)管理器 (和配置文件方式一樣)--> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入dataSource --> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 第二步: 開啟事務(wù)注解 --> <tx:annotation-driven transaction-manager="dataSourceTransactionManager" /> <!-- 第三步 在方法所在類上加注解 --> <!-- 對象生成及屬性注入 --> <bean id="ordersService" class="cn.itcast.service.OrdersService"> <property name="ordersDao" ref="ordersDao"></property> </bean> <bean id="ordersDao" class="cn.itcast.dao.OrdersDao"> <property name="jdbcTemplate" ref="jdbcTemplate"></property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Spring的編程式事務(wù)和聲明式事務(wù)詳解
- Spring聲明式事務(wù)和@Aspect的攔截順序問題的解決
- spring聲明式事務(wù)管理解析
- spring聲明式事務(wù)解析
- spring 聲明式事務(wù)實(shí)現(xiàn)過程解析
- Spring實(shí)戰(zhàn)之使用TransactionProxyFactoryBean實(shí)現(xiàn)聲明式事務(wù)操作示例
- Spring實(shí)戰(zhàn)之使用注解實(shí)現(xiàn)聲明式事務(wù)操作示例
- 詳解Spring學(xué)習(xí)之聲明式事務(wù)管理
- 關(guān)于Spring中聲明式事務(wù)的使用詳解
相關(guān)文章
Java用Arrays.asList初始化ArrayList實(shí)例方法
在本篇文章里小編給大家分享的是關(guān)于Java中使用Arrays.asList初始化ArrayList的知識點(diǎn)內(nèi)容,需要的朋友們參考下。2019-10-10
Java結(jié)合Swing實(shí)現(xiàn)龍年祝福語生成工具
Swing是一個為Java設(shè)計(jì)的GUI工具包,屬于Java基礎(chǔ)類的一部分,本文將使用Java和Swing實(shí)現(xiàn)龍年祝福語生成工具,感興趣的小伙伴可以了解下2024-01-01
如何為?Spring?Boot?項(xiàng)目配置?Logback?日志
由于?Spring?Boot?的默認(rèn)日志框架選用的?Logback,再加上?Log4j2?之前爆過嚴(yán)重的漏洞,所以我們這次就只關(guān)注?Logback,本文重點(diǎn)給大家介紹如何為?Spring?Boot?項(xiàng)目配置?Logback?日志,感興趣的朋友跟隨小編一起看看吧2024-07-07
SpringBoot2.1 RESTful API項(xiàng)目腳手架(種子)項(xiàng)目
這篇文章主要介紹了SpringBoot2.1 RESTful API項(xiàng)目腳手架(種子)項(xiàng)目,用于搭建RESTful API工程的腳手架,只需三分鐘你就可以開始編寫業(yè)務(wù)代碼,不再煩惱于構(gòu)建項(xiàng)目與風(fēng)格統(tǒng)一,感興趣的小伙伴們可以參考一下2018-12-12
自制Java工具實(shí)現(xiàn)翻譯鼠標(biāo)選中文本
這篇文章主要為大家詳細(xì)介紹了如何自制Java工具實(shí)現(xiàn)ctrl+c+c翻譯鼠標(biāo)選中文本,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2024-01-01
Java ZooKeeper分布式鎖實(shí)現(xiàn)圖解
ZooKeeper是一個分布式的,開放源碼的分布式應(yīng)用程序協(xié)調(diào)服務(wù),是Google的Chubby一個開源的實(shí)現(xiàn),是Hadoop和Hbase的重要組件。它是一個為分布式應(yīng)用提供一致性服務(wù)的軟件,提供的功能包括:配置維護(hù)、域名服務(wù)、分布式同步、組服務(wù)等2022-03-03

