简体   繁体   English

@Transactional和继承

[英]@Transactional and inheritance

I used to add @Transactional annotations to all spring services (classes). 我曾经在所有Spring服务(类)中添加@Transactional注释。 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 ). (当然,如果它不应该,我们会将@Transational与其他参数一起添加到方法中。)我试图找到一些关于@Transactional继承的有用信息,阅读@Inherited (看起来@Transactional@Inherited ) 。 I experimented with rollbackFor and noRollbackFor for the following example, and it looks like @Transactional in GenericService worked for doSmthSpecific . 我为以下示例尝试了rollbackFornoRollbackFor ,看起来GenericService @Transactional适用于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 . 如果GenericService是一个接口,我认为它不会起作用 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. 我想这更像是“纠正我,如果我错了”的问题,我想知道是否真的可以将@Transactional添加到超类中,如果我在这里遗漏了一些东西。 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... 您可以在接口定义,接口上的方法,类定义或类的公共方法之前放置@Transactional注释...

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. Spring建议您只使用@Transactional注释来注释具体类(以及具体类的方法),而不是注释接口。 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. 您当然可以将@Transactional注释放在接口(或接口方法)上,但这只能在您使用基于接口的代理时按预期工作。

Later they go on to explain that it doesn't work when you're using class-based proxies or aspectj weaving. 后来他们继续解释当你使用基于类的代理或aspectj编织时它不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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