Antonio Dragos
Antonio Dragos

Reputation: 2873

Where to specify @Transactional annotation in a Spring Boot app?

In the context of a recent Spring Boot app (v. 2.7.0), there are a number of options for where the @Transactional annotation is applied

Controller or Service?

Almost universally it seems that service is recommended, but it's not entirely clear why.

Implementation class or interface?

Assuming we choose to apply the annotation to our services and those services implement an interface, should we annotate the service interface or the implementation class?

In older versions of the Spring docs, it was recommended to annotate the class

Spring recommends that you only annotate concrete classes (and methods of concrete classes) with the @Transactional annotation, as opposed to annotating interfaces. You certainly can place the @Transactional annotation on an interface (or an interface method), but this works only as you would expect it to if you are using interface-based proxies. The fact that Java annotations are not inherited from interfaces means that if you are using class-based proxies (proxy-target-class="true") or the weaving-based aspect (mode="aspectj"), then the transaction settings are not recognized by the proxying and weaving infrastructure, and the object will not be wrapped in a transactional proxy, which would be decidedly bad.

But this advice does not appear in the 5.2.X version of the docs, so I'm wondering if it still applies? Based on my testing it seems that applying the @Transactional annotation to interfaces does work in a Spring Boot app with the default proxying behaviour.

Upvotes: 0

Views: 963

Answers (1)

armandino
armandino

Reputation: 18572

@Transactional is most commonly used at service level, though there is nothing stopping you from making your controller methods transactional. It really depends on how you structure your application.

IMHO making your service layer transactional is a better approach. It is typically at this level that you might be calling other persistence methods (DAOs, repositories, etc). There could be reads/writes across multiple tables, so it makes the service layer a good place to define transaction boundaries.

Upvotes: 0

Related Questions