在哪里应该放置@Transactional注释:在接口定义或实现类? [英] Where should I put @Transactional annotation: at an interface definition or at an implementing class?
问题描述
标题中的问题:
@Transactional (readonly = true)
public interface FooService {
void doSmth ();
}
public class FooServiceImpl implements FooService {
...
}
vs
public interface FooService {
void doSmth ();
}
@Transactional (readonly = true)
public class FooServiceImpl implements FooService {
...
}
推荐答案
从 http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html
Spring团队的建议是,您只需使用
@Transactional
注释注释具体类, 您当然可以在接口(或接口方法)上放置@Transactional
注释,但这只会按您期望的方式工作它到如果你使用基于接口的代理。注释不是继承的事实意味着如果您使用基于类的代理,那么基于类的代理基础结构将不会识别事务设置,并且对象不会被包装在事务代理中(这将是决定性的坏)。所以,请采取Spring团队的建议,并且只用@Transactional
注释来注释具体类(以及具体类的方法)。
The Spring team's recommendation is that you only annotate 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 will only work as you would expect it to if you are using interface-based proxies. The fact that annotations are not inherited means that if you are using class-based proxies then the transaction settings will not be recognised by the class-based proxying infrastructure and the object will not be wrapped in a transactional proxy (which would be decidedly bad). So please do take the Spring team's advice and only annotate concrete classes (and the methods of concrete classes) with the@Transactional
annotation.
注意:由于这个机制是基于代理,只有通过代理进入的外部方法调用将被拦截。这意味着自我调用目标对象调用目标对象的一些其他方法,即使调用的方法标记有 @Transactional
!
Note: Since this mechanism is based on proxies, only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with @Transactional
!
(强调添加到第一句,其他强调从原始。)
(Emphasis added to the first sentence, other emphasis from the original.)
这篇关于在哪里应该放置@Transactional注释:在接口定义或实现类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!