问题描述
我曾经为所有 spring 服务(类)添加 @Transactional
注释.然后我想:如果交易行为应该相同,我真的必须这样做吗?(当然,如果不应该,我们会在方法中添加带有其他参数的 @Transational
.)我试图找到一些关于 @Transactional
继承的有用信息,阅读关于 @Inherited
(看起来 @Transactional
是 @Inherited
).我在下面的例子中试验了 rollbackFor
和 noRollbackFor
,它看起来像 GenericService
中的 @Transactional
为 doSmthSpecific.
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() {
}
}
如果 GenericService
是一个接口,我认为 它不起作用.我想这更像是如果我错了,请纠正我"的问题,我想知道将 @Transactional
添加到超类是否真的可以,如果我在这里遗漏了什么.详细解释(或此类解释的链接)将不胜感激.
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.
推荐答案
引用 文档
您可以在接口定义、接口上的方法、类定义或类上的公共方法之前放置@Transactional 注解...
他们还建议不要注释接口/接口方法.
They also recommend against annotating interfaces/interface methods.
Spring 建议您只使用 @Transactional 注释来注释具体类(和具体类的方法),而不是注释接口.您当然可以将 @Transactional 注释放在接口(或接口方法)上,但是如果您使用基于接口的代理,这只能像您期望的那样工作.
后来他们继续解释说,当您使用基于类的代理或 aspectj 编织时,它不起作用.
Later they go on to explain that it doesn't work when you're using class-based proxies or aspectj weaving.
这篇关于@Transactional 和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!