Spring-事务管理(基于xml配置文件进行声明式事务管理)
1.在spring配置文件进行配置
第一步:配置事务管理器
第二步:配置通知
第三步:配置切入点和切面
<?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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 开启组件扫描-->
<context:component-scan base-package="com.orzjiangxiaoyu.spring"></context:component-scan>
<!-- 数据库连接池 -->
<context:property-placeholder location="mysqljdbc.properties"></context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClassName" value="${jdbc.driverClassName}"></property>
</bean>
<!-- JdbcTemplate对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
<!-- 注入dataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 创建事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入dataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置通知-->
<tx:advice id="txadvice">
<!-- 配置事务参数 -->
<tx:attributes>
<!-- 指定哪种规则方法上面添加事务 -->
<tx:method name="accountMoney" propagation="REQUIRED"/>
<!-- <tx:method name="account*"></tx:method>-->
</tx:attributes>
</tx:advice>
<!-- 配置切入点切面 -->
<aop:config>
<!-- 配置切入点-->
<aop:pointcut id="pt" expression="execution(* com.orzjiangxiaoyu.spring.service.BankService.*(..))"/>
<!-- 配置切面-->
<aop:advisor advice-ref="txadvice" pointcut-ref="pt"></aop:advisor>
</aop:config>
</beans>
package com.orzjiangxiaoyu.spring.service; import com.orzjiangxiaoyu.spring.dao.BankDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * @author orz * @create 2020-08-18 16:32 */ @Service public class BankService { @Autowired private BankDao bankDao; //转账方法 //声明式 public void accountMoney() { //少钱操作 bankDao.reduceMoney(); //手动抛出异常 System.out.println(1/0); //多钱操作 bankDao.addMoney(); } }

浙公网安备 33010602011771号