标题注解配置的方式使用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的事务管理的注解配置的方式已经完成另了,如有疑问请下下方留言看到后会在第一时间恢复的。