Spring @Transactional and Private Methods [Snippets]
Working around Spring's @Transactional and private methods using Java 8's lambdas can result in cleaner solutions and less fragmented objects.
Join the DZone community and get the full member experience.
Join For FreeAs most of you probably know, due to the very nature of the solution, Spring's @Transactional annotation does not work on private methods unless you're using the AspectJ mode (which, in my experience, most of us aren't). In such a case, the only solution to the problem is to access the transactional method through an auto-wired bean, either via self-injection or delegation.
The problem that I have with the first approach is that it screams, "I AM A HACK!" And I obviously don't like when my code screams that. The problem that I have with the second one is not the mere fact of letting another object do the work, but the way we achieve that, i.e. by creating these strange beans with arbitrary names just to get it working.
With Java 8 "in the hood" for a good few years and a growing popularity of other languages with functional features, we can do better. Here's my way to do that using lambdas:
// SomeBean.java :
@Service
public class SomeBean {
@Autowired
private TransactionHelper helper;
public void nonTransactional() {
// non-transactional stuff
String result = helper.withTransaction(() -> gimmeTheResult());
// or:
helper.withTransaction(() -> fireAndForget());
// continue...
}
}
// TransactionHelper.java :
@Service
public class TransactionHelper {
@Transactional
public <T> T withTransaction(Supplier<T> supplier) {
return supplier.get();
}
@Transactional
public void withTransaction(Runnable runnable) {
runnable.run();
}
}
Obviously, this ain't rocket science, and it's not something uncommon in other frameworks. Yet still, for some reason, more often than the code above, I see something like this:
// SomeBean.java :
@Service
public class SomeBean {
@Autowired
private TransactionalPart transactionalPart;
public void nonTransactional() {
// non-transactional stuff
transactionalPart.execute();
// continue...
}
}
// TransactionalPart.java :
@Service
public class TransactionalPart {
@Transactional
public void execute() {
// do stuff
}
}
I believe that the first solution is cleaner, arguably simpler, and does not unnecessarily fragment objects. What about you? Let me know in the comments!
Opinions expressed by DZone contributors are their own.
Comments