Reputation: 9764
I used to add @Transactional
annotations to all Spring services (classes). And then I thought: do I really have to, if the transactional behavior should be the same? (Of course, if it shouldn't, we would add @Transational
with other parameters to methods.) I tried to find some useful information about inheritance with @Transactional
, read about @Inherited
(and it looks like @Transactional
is @Inherited
). I experimented with rollbackFor
and noRollbackFor
for the following example, and it looks like
@Transactional
in GenericService
worked for doSmthSpecific
.
@Transactional
public abstract class GenericService {
public void doSmthGeneric() {
}
}
public class SpecificService extends GenericService {
public void doSmthSpecific() {
}
}
And in case GenericService
was an interface, I think it wouldn't work. I guess it's more like "correct me if I'm wrong" question, I'd like to know if it's actually all right to add @Transactional
to superclass only, and if I'm missing something here. A detailed explanation (or a link to such explanation) would be appreciated.
Upvotes: 4
Views: 2966
Reputation: 36777
Quoting the docs
You can place the @Transactional annotation before an interface definition, a method on an interface, a class definition, or a public method on a class...
They also recommend against annotating interfaces/interface methods.
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.
Later they go on to explain that it doesn't work when you're using class-based proxies or aspectj weaving.
Upvotes: 2