(1)前期准备
https://blog.csdn.net/weixin_45460315/article/details/105176089
(2)修改application.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:centext="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
<!-- 加入扫描 -->
<centext:component-scan base-package="com.linxin.spring.dao"></centext:component-scan>
<centext:component-scan base-package="com.linxin.spring.service"></centext:component-scan>
<!-- 加载文件 -->
<centext:property-placeholder location="classpath:db.properties"/>
<!-- spring管理c3p0数据源 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- Jdbctemplate -->
<bean name="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 事务管理 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 开启注解事务管理 -->
<tx:annotation-driven/>
</beans>
(3)修改serice下的实现类
package com.linxin.spring.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.linxin.spring.dao.AccountDao;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Resource(name="accountDao")
private AccountDao accountDao;
@Override
@Transactional(propagation = Propagation.REQUIRED,readOnly = false,isolation = Isolation.READ_COMMITTED)
public void transfer(Integer from, Integer to, Double money) {
accountDao.addMoney(to, money);
int a=1/0;
accountDao.subMoney(from, money);
}
}
(4)完成其余不变