SpringMVC、MyBatis 声明式事务管理

本文介绍了如何在Spring MVC和MyBatis环境下配置声明式事务管理。通过调整组件扫描顺序及配置,确保Service层能正确应用事务策略。文章详细展示了如何在配置文件中设置事务管理器及切面来实现细粒度的事务控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


    Spring事务管理分为传统的全局事务管理和本地事务管理,使得在任何环境中都可以使用统一的事务管理模型,你可以写一次代码,然后在不同的环境从你的代码里面配置不同的事务管理策略,Spring提供两种事务管理策略:一种是声明式事务管理策略,另一种是编程式事务管理策略,这里主要介绍声明式事务管理策略。
        由于采用的是SpringMVC、 MyBatis,故统一采用了标注来声明Service、Controller 。
        
由于服务器启动时加载配置文件的顺序为web.xml---applicationContext-*.xml(Spring的配置文件)---springMVC-servlet.xml(SpringMVC的配置文件),由于applicationContext-*.xmll配置文件中Controller会先进行扫描装配,但是此时service还没有进行事务增强处理,得到的将是原样的Service(没有经过事务加强处理,故而没有事务处理能力),所以我们必须在applicationContext-*.xml中不扫描Controller,此时applicationContext-*.xml中的配置如下:
<!-- applicationContext.xml中,去掉对controller的扫描 -->
<context:component-scan base-package="com.mpto">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

同理,在springMVC-servlet.xml 中去掉对 service的扫描,加入对controller的扫描

<context:component-scan base-package="com.mpto">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>


最后,配置声明式事务管理,事务的配置只有在 applicationContext.xml 中才会起作用
<bean id="txManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
</bean>
<!-- spring declarative transaction management -->
<aop:config>
    <aop:pointcut id="myServiceMethods"
        expression="execution(* com.mpto.*.biz.impl.*.*(..))" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="myServiceMethods" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
    <tx:attributes>
        <tx:method name="get*" read-only="true" />
        <tx:method name="find*" read-only="true" />
        <tx:method name="*" rollback-for="CustomException" />
    </tx:attributes>
</tx:advice>

注意:事务作用在service 上,不能在service里面加try catch去捕获异常,否则不能被spring拦截到,事务将失效

 到此SpringMVC声明式事务管理配置完成
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值