spring transaction失效的几种情况

1.首先检查配置,在项目的spring配置文件检查是否配置开启事务:

  1. <bean id="transactionManager"  
  2.     class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  3.     <property name="dataSource" ref="routeDataSource" />  
  4. </bean>  
  5.   
  6. <!-- 事务 -->  
  7. <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />  

2.同一个类中, 一个未标注@Transactional的方法去调用标有@Transactional的方法, 事务会失效

If you use (default) Spring Proxy AOP, then all AOP functionality provided by Spring (like @Transational) will only be taken into account if the call goes through the proxy. -- This is normally the case if the annotated method is invoked from another bean.

3:在非public方法上标注@Transactional, 事务无效

When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private 

or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured

 transactional settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods.

   <!-- 事务设置 -->
   <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
       <property name="entityManagerFactory" ref="entityManagerFactory"/>
   </bean>
<!-- 事务使用AspectJ进行编译时Weave -->
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>

5:springboot+mybatis事务管理_springboot mybatis 事务-CSDN博客


虽然 @Transactional 注解可以作用于接口、接口方法、类以及类方法上,但是 Spring 建议不要在接口或者接口方法上使用该注解,因为这只有在使用基于接口的代理时它才会生效。另外, @Transactional 注解应该只被应用到 public 方法上,这是由 Spring AOP 的本质决定的。如果你在 protected、private 或者默认可见性的方法上使用 @Transactional 注解,这将被忽略,也不会抛出任何异常。

默认情况下,只有来自外部的方法调用才会被AOP代理捕获,也就是,类内部方法调用本类内部的其他方法并不会引起事务行为,即使被调用方法使@Transactional注解进行修饰。

在使用@Transactional注解前,请在启动类上加上注解@EnableTransactionManagement来开启事务。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值