关于springboot中的事务注解

前: 在项目运行时,由于某条数据插入失败,发现事务未起作用

看了下启动类并没有加@EnableTransactionManagement注解开启事务

@EnableScheduling
@SpringBootApplication
@MapperScan(basePackages = "com.huofu.koudai.mapper")
@EnableConfigurationProperties(OssProperties.class)
@EnableTransactionManagement
public class AppApplication {

     public static void main(String[] args) {

          SpringApplication.run(AppApplication.class, args);
         }


    @Bean
    public OssTemplate ossTemplate(OssProperties properties) {
        return new OssTemplate(properties);
    }
}

在添加了注解后发现事务仍然不起作用,查阅资料后发现springboot的自动装配自动开启了事务管理

具体流程如下:

查看启动类的核心注解

找到自动装配注解

进入自动装配注解查看选择器

 继续进入选择器,查看选择器所导入的类,找到自动获得的Entity

找到该方法

 此方法传入一个元数据

此方法中的loadFactoryNames方法, 就是加载所有的组件的全限类

进入 loadFactoryNames方法,此方法第一个参数为类型,第二个参数为类加载器,返回值为本类的loadSpringFactories方法

 查看loadSpringFactories方法

getResources获取自动配置组件
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

找到public class AutoConfigurationImportSelector类所在的包,查看它的META-INF文件,找到spring.factories文件:

 进入此文件我们可以看到,事务的自动装配配置类,当Springboot容器启动的时候,首先会扫描此文件,会自动为我们加载事务相关信息

因此,springboot项目并不需要@EnableTransactionManagement注解开启事务

接下来,继续查找事务不生效的原因:

最终查询到在Spring的Transactional的API文档中,有以下一段说明:

If no rules are relevant to the exception, it will be treated like DefaultTransactionAttribute (rolling back on runtime exceptions)

意思是:如果没有与异常相关的规则,它将被视为默认事务属性(即回滚运行时异常)。

因此需要指定注解属性为@Transactional(rollbackFor = Exception.class),这样,便可回滚所有异常.

总结:

① springboot自动装配会自动开启事务,不需要@EnableTransactionManagement注解开启事务

② spring声明式事务,需要在@Transactional注解添加rollbackFor指定回滚类型,否则默认只回滚运行时异常

 

  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值