【问题标题】:Transaction synchronization in Spring BootSpring Boot 中的事务同步
【发布时间】:2018-08-03 17:02:27
【问题描述】:

我有一个小型 Spring Boot 应用程序,其中 spring-boot-starter-webspring-boot-starter-data-jpapostgresql 作为依赖项。

我能够使用@Transactional 注释并使用JPA 来获取实体并将其保存到数据库中。但是,如果我要通过注册同步添加afterCommit/afterCompletion 挂钩,它会给出IllegalStateExceptionTransaction synchronization is not active

TransactionSynchronizationManager.registerSynchronization(
     new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            //this doesn't get called
            log.info("do something here");
        }
    });

执行TransactionSynchronizationManager.initSynchronization(); 会消除错误,但不会调用挂钩(例如:即使事务已提交,也不会调用afterCommit 挂钩。)

关于如何调试的任何线索?

【问题讨论】:

  • 提交后你想做什么?
  • 新的 TransactionSynchronizationAdapter() 已弃用

标签: spring spring-boot spring-data-jpa spring-transactions


【解决方案1】:

原来我忘记包含用于为具有@Transactional 注释的 bean 创建 AoP 代理的构建插件。

在没有这个插件的情况下,不会生成代理,代码会以非事务方式运行;除了当它进入JpaRepository 方法时,它会在调用期间创建一个短期事务(例如save/findAll/delete)。

这是我错过的插件,包括在我的 pom.xml 中(这是由 spring initializr (https://start.spring.io/) 在 pom 输出中生成的,但我一开始并没有注意到它,也没有将它复制到我的pom)

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

【讨论】:

    【解决方案2】:

    我认为您需要@TransactionalEventListener 注释。它支持钩子 BEFORE_COMMIT、AFTER_ROLLBACK、AFTER_COMPLETION、AFTER_COMMIT 和 AFTER_ROLLBACK。

    这篇文章的更多信息:Better application events in Spring Framework 4.2

    【讨论】:

      猜你喜欢
      • 2019-03-16
      • 2019-10-03
      • 2019-10-05
      • 1970-01-01
      • 2018-05-01
      • 2015-06-08
      • 2019-12-09
      • 2012-03-03
      • 2012-06-03
      相关资源
      最近更新 更多