简体   繁体   中英

@Transactional and inheritance

I used to add @Transactional annotations to all spring services (classes). And then I thought: do I really have to, if the transactinal behaviour 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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM