声明式事务(Declarative Transaction Management)是Spring框架提供的一种对程序事务进行管理的方式。这种管理方式的核心思想是采用声明的方式(通常是在配置文件中声明,而非在代码中硬编码)来处理事务,从而简化开发过程,降低开发者处理复杂事务的难度。
在声明式事务中,开发者通过注解(如@Transactional)或基于配置的XML来管理事务,而不需要依赖底层API进行硬编码。这使得业务逻辑对象无需意识到它们正处于事务管理之中,因为事务管理属于系统层面的服务,而不是业务逻辑的一部分。因此,当需要改变事务管理策略时,只需在配置文件中重新配置即可,无需修改代码并重新编译,从而大大提高了维护的便利性。
转账案例
- dao接口
package com.powernode.bank.dao;
import com.powernode.bank.pojo.Account;
public interface AccountDao {
//根据账号查询账户信息
Account selectByActno(String actno);
//更新账户信息
int update(Account act);
//保存账户信息
int insert(Account act);
}
- dao实现接口
package com.powernode.bank.dao.impl;
import com.powernode.bank.dao.AccountDao;
import com.powernode.bank.pojo.Account;
import jakarta.annotation.Resource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class AccountDaoImpl implements AccountDao {
@Resource
private JdbcTemplate jdbcTemplate;
@Override
public Account selectByActno(String actno) {
String sql = "select actno,balance from t_act where actno = ?";
Account account = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Account.class), actno);
System.out.println("笑"+account);
return account;
}
@Override
public int update(Account act) {
String sql = "update t_act set balance = ? where actno = ?";
int update = jdbcTemplate.update(sql, act.getBalance(), act.getActno());
return update;
}
@Override
public int insert(Account act) {
String sql = "insert into t_act values(?,?)";
return jdbcTemplate.update(sql,act.getActno(),act.getBalance());
}
}
- pojo实体类
package com.powernode.bank.pojo;
public class Account {
private String actno;
private Double balance;
public Account() {
}
public Account(String actno, Double balance) {
this.actno = actno;
this.balance = balance;
}
public String getActno() {
return actno;
}
public void setActno(String actno) {
this.actno = actno;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Account{" +
"actno='" + actno + '\'' +
", balance=" + balance +
'}';
}
}
- service接口
package com.powernode.bank.service;
public interface AccountService {
void transfer(String fromActno, String toActno, double money);
}
- service实现类
package com.powernode.bank.service.impl;
import com.powernode.bank.dao.AccountDao;
import com.powernode.bank.pojo.Account;
import com.powernode.bank.service.AccountService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AccountServiceImpl implements AccountService {
@Resource
private AccountDao accountDao;
//控制事务
@Override
public void transfer(String fromActno, String toActno, double money) {
//查询余额
Account fromAct = accountDao.selectByActno(fromActno);
if (fromAct.getBalance() < money){
throw new RuntimeException("余额不足!!");
}
//余额充足
Account toAct = accountDao.selectByActno(toActno);
//将内存中两个对象的余额先修改
fromAct.setBalance(fromAct.getBalance() - money);
toAct.setBalance(toAct.getBalance() + money);
//数据库更新
int count = accountDao.update(fromAct);
//模拟异常
/* String s = null;
s.toString();*/
count += accountDao.update(toAct);
if (count !=2){
throw new RuntimeException("转账失败,联系银行");
}
}
}
- spring.xml配置文件
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--组件扫描-->
<context:component-scan base-package="com.powernode.bank"/>
<!--配置数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.1.41:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="Abc123***"/>
</bean>
<!--配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务管理器-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--开启事务注解驱动器-->
<!-- <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
<!--配置通知的transfer方法-->
<tx:attributes>
<tx:method name="transfer" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
</tx:attributes>
</tx:advice>
<!--配置切面-->
<aop:config>
<!--切点-->
<aop:pointcut id="txPointcut" expression="execution(* com.powernode.bank.service..*(..))"/>
<!--切面 = 事务通知+切点-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
</beans>
- 测试
@Test
public void testNoAnnotation() {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring.xml");
AccountService accountServiceImpl = classPathXmlApplicationContext.getBean("accountServiceImpl", AccountService.class);
try {
accountServiceImpl.transfer("act-001", "act-002", 10000);
System.out.println("转账成功");
} catch (Exception e){
e.printStackTrace();
}
}
数据库截图