今天来记录一下在SSM项目中经常使用到的事务管理的配置,其实在spring中事务管理有很多方法,但今天我用的是最简单的这种(还不是因为懒~)aop自动管理事务。
1.首先我们需要有一个整合好的SSM框架项目,具体搭建步骤可以参考我的另一篇文章:最新版的SSM框架spring5.0搭建教程
2.下面就进入正题 了,我们只需要在spring-mybatis.xml文件中配置几个地方就可以了。
---->导入aop的引用:
xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
---->配置spring的事务管理器(在我之前的配置文件中已经配置过了):
<!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
---->配置aop全局事务管理(我本机写的demo中业务不算复杂,也为了方便演示,所以直接切到controller层了,切入点可以根据自己的项目需要自行设置):
<!--aop全局事务管理(下面基于controller层)-->
<aop:config>
<aop:pointcut id="allControllerMethods"
expression="execution(* com..controller..*(..))"/>
<aop:advisor advice-ref="defaultTransactionAdvice"
pointcut-ref="allControllerMethods"/>
</aop:config>
---->配置事务管理的通知(具体指定aop拦截到的哪些方法需要创建/使用事务):
<tx:advice id="defaultTransactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--<tx:method name="*" isolation="DEFAULT"-->
<!--propagation="REQUIRED" no-rollback-for="java.lang.RuntimeException" timeout="100"/>-->
<!--<tx:method name="*" read-only="true"/>-->
<!-- 以方法为单位,指定方法应用什么事务属性 isolation:隔离级别 propagation:传播