Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing code before and after @Transactional method

Tags:

java

spring

We have a Spring based application with a service layer which is annotated with @Transactional. We need to have code run before and after some transactional methods for the following reasons:

  1. We need to synchronize access to the method based on a key. The thread needs to block before the start of the transaction.
  2. We need to post a message on a queue if the transaction succeeds.

The options seem to be:

  1. Create a class with similar methods to the service that can run the @Transactional method in a synchronized block and check for the return then post the message (would need a separate class due to AOP proxy problem). Services calling services, not nice, feels like a work-around.
  2. Write an aspect to wrap around the @Transactional AOP which can do the synchronization and message posting. Might work but would rather avoid AOP.
  3. Move the transaction down to the domain layer. Not desirable or possibly even feasible with the current implementation due to the way domain methods are reused in different workflows.
  4. Code the transaction by hand in the service method and scrap @Transactional.

I would imagine this is a fairly common requirement. Probably I am missing an option 5, which is the obvious one!

like image 369
Dan Saunders Avatar asked Feb 24 '23 14:02

Dan Saunders


1 Answers

I think I'd go with 2 unless you have some specific reasons to avoid AOP. Your problem is a classic example of where AOP can be used and it looks pretty good in the result. Here is a nice example of how to implement that (if you didn't read that already): Advising transactional operations

If AOP is really not an option, I'd go the 'Otherwise' option proposed by @Lawrence McAlpin.

like image 122
bezmax Avatar answered Feb 26 '23 22:02

bezmax