想象一个银行转钱的场景,如果当转账的时候操作失误,然后钱扣了,但接收人的账号却没有钱到账,这多亏呀,所以这里就需要用到事务,事务的原子性就是事务内一个操作失败了就回滚到原来的状态,从而解决了这尴尬的局面。下面就用spring来实现上面的场景。
老套路,先创建一个接口:
package exchange;
public interface account {
void addMoney(Integer id,Double money);
void mulMoney(Integer id,Double money);
}
随后实现这些方法
package exchange;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class exchangeMethod extends JdbcDaoSupport implements account {
@Override
public void addMoney(Integer id, Double money) {
super.getJdbcTemplate().update("update t_user set money = money + ? where id = ?",money,id);
}
@Override
public void mulMoney(Integer id, Double money) {
super.getJdbcTemplate().update("update t_user set money = money - ? where id = ?",money,id);
}
}
然后创建一个实现转钱功能的方法
package exchange;
public class accountService {
public void setEm(exchangeMethod em) {
this.em = em;
}
private exchangeMethod em;
public void exchangeMoney(Integer from,Integer to,Double money){
em.mulMoney(from,money);
// int i = 1/0; 特地弄成故障的代码
em.addMoney(to,money);
}
}```
再来把类都配置到spring容器中
<?xml version="1.0" encoding="UTF-8"?>
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property> <!--spring封装的事务核心管理器-->
</bean>
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"></property> <!--spring封装的事务模板-->
</bean>
<tx:advice transaction-manager="transactionManager" id="txAdvice"> <!--把事务变成通知-->
<tx:attributes>
<tx:method name="exchangeMoney" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/> <!--业务方法配置-->
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="accS" expression="execution(* exchange.accountService.exchangeMoney(..))"></aop:pointcut>
<aop:advisor advice-ref="txAdvice" pointcut-ref="accS"></aop:advisor>
</aop:config>
<bean name="em" class="exchange.exchangeMethod">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean name="as" class="exchange.accountService">
<property name="em" ref="em"></property>
</bean>
``` 最后写一个demo来实现这个功能
package exchange;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class demo1 {
public static void main(String args[]) {
ApplicationContext ac = new ClassPathXmlApplicationContext("exchange/applicationContext.xml");
accountService acc = (accountService) ac.getBean("as");
acc.exchangeMoney(2,3,100d);//d是把100转换为Double类型
}
}