Spring的声明式事务处理的使用注解配置方式

标题注解配置的方式使用aop事务管理

第一步创建maven工程:
第二步配置AccountDaoImpl.java dao的实现类类

@Repository
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

    @Autowired
    public void setDi(DataSource dataSource){
        super.setDataSource(dataSource);
    }

}

第三步创建Service的实现类:

//声明这是个Service类
@Service
//什么开启事务(只读)
@Transactional(readOnly = true)
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;


    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);

    }
    //声明事务(可写)
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED)
    public void transfer( String sourceName,  String targetName,  Float money) {
        System.out.println("transfer....");

        //2.1根据名称查询转出账户
        Account source = accountDao.findAccountByName(sourceName);
        //2.2根据名称查询转入账户
        Account target = accountDao.findAccountByName(targetName);
        //2.3转出账户减钱
        source.setMoney(source.getMoney() - money);
        //2.4转入账户加钱
        target.setMoney(target.getMoney() + money);
        //2.5更新转出账户
        accountDao.updateAccount(source);

        int i=1/0;

        //2.6更新转入账户
        accountDao.updateAccount(target);

    }
}

小知识点:方法级别的事务声明会覆盖类级别的声明
第四步:配置applicationContext.xml
引入空间和声明:

 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"

http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"


配置事务管理器:

<!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

开启事务管理支持:

 <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

配置开启组件扫描:

 <context:component-scan base-package="com.itheima"></context:component-scan>

到此spring的事务管理的注解配置的方式已经完成另了,如有疑问请下下方留言看到后会在第一时间恢复的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值