Srping——Spring中的声明式事务
一、声明式事务
在Spring中支持两种事务处理机制:
- 编程式事务:把事务的代码都写在业务中
- 声明式事务:使用AOP横切进去(一般会使用声明式事务)
我们要开启Spring的声明式事务处理功能,在Spring配置文件种创建一个DataSourceTransactionManager对象,事务管理器是需要一个数据源dataSource的
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
然后我们还需要配置声明事务通知:tx,并在tx内配置需要事务管理的方法。
最后我们还需要将配置好的事务使用aop横切进去
二、Spring配置事务步骤
1.导包:
需要导入aspectjweaver包,实现aop织入
<!--aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.3</version>
</dependency>
spring-jdbc的包
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
2.需要配置一个事务管理器,其中参数需要一个数据源
- 配置数据源:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&
useUnicode=true&characterEncoding=utf-8"/>
</bean>
- 配置事管理器:
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--使用构造的原因是:没有set方法,不能使用set注入-->
<constructor-arg index="0" ref="dataSource"/>
</bean>
3.配置声明式事务通知
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--
name:需要使用事务管理的方法
propagation:配置事务的传播特性
REQUIRED:如果没有事务,就新建一个事务。
-->
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
4.配置aop织入事务
<aop:config>
<!--切入点-->
<aop:pointcut id="txPointcut" expression="execution(* com.muhan.dao.UserDaoImpl.*(..))"/>
<!--通知-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>