Spring JDBC申明式事务配置过程
-
声明式事务指在不修改源码情况下通过配置形式自动实现事务控制,声明式事务的本质就是AOP环绕通知。
-
当目标方法执行成功时,自动提交事务。
-
当目标方法抛出运行时异常时,自动事务回滚。
配置过程
-
配置TransationManager事务管理器
-
配置事务通知与事务属性
-
为事务通知绑定PointCut切点
##使用流程如下:
声明式事务,底层是依赖AOP 面向切面编程的。所以需要导入AOP依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
在配置文件中增加一系列命名空间,包括事务、aop等:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
事务管理器配置事务管理器
<!--事务管理器:用于创建事务/提交/回滚-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--事务通知配置,决定哪些方法使用事务,哪些不使用-->
<tx:advice transaction-manager="transactionManager" id="txAdvice">
<tx:attributes>
<!--目标方法名为batchAdd时,启动声明式事务,成功提交,运行异常时回滚-->
<tx:method name="batchAdd" propagation="REQUIRED"/>
<!--设置不使用事务-->
<tx:method name="find*" propagation="NOT_SUPPORTED" read-only="true"/>
<tx:method name="get*" propagation="NOT_SUPPORTED" read-only="true"/>
<!--其他情况-->
<tx:method name="*" propagation="NOT_SUPPORTED" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--定义声明式事务的作用范围-->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(public * top.xiongmingcai..*Service.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>