I have a small Spring Boot application with spring-boot-starter-web
, spring-boot-starter-data-jpa
, and postgresql
as dependencies.
I'm able to use the @Transactional
annotation and use JPA to fetch and save entities to the database. However, if I were to add afterCommit
/ afterCompletion
hooks via registering a synchronization, it gives an IllegalStateException
saying that Transaction synchronization is not active
.
TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
//this doesn't get called
log.info("do something here");
}
});
Doing TransactionSynchronizationManager.initSynchronization();
gets rid of the error, but the hooks don't get called (eg: the afterCommit
hook doesn't get called even though the transaction has committed.)
Any clues on how to debug this?
It turned out that I had forgotten to include the build plugin that is used to create the AoP-proxies for beans having @Transactional annotations.
In the absence of this plugin, no proxies would get generated, and the code would run non-transactionally; except for when it enters the JpaRepository
methods where it would create a short-lived transaction for the duration of the call (such as save
/ findAll
/ delete
).
This is the plugin that I missed including in my pom.xml (this got generated in the pom output by the spring initializr ( https://start.spring.io/ ) but I didn't notice it at first and didn't copy it over into my pom)
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
I think you need @TransactionalEventListener
annotation. It supports hooks BEFORE_COMMIT, AFTER_ROLLBACK, AFTER_COMPLETION, AFTER_COMMIT and AFTER_ROLLBACK.
More info in this post: Better application events in Spring Framework 4.2 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.