我应该在哪里把@Transactional注释:在接口定义或实现类? [英] Where should I put @Transactional annotation: at an interface definition or at an implementing class?
问题描述
在code标题的问题:
@Transactional(只读=真)
公共接口FooService接口{
无效doSmth();
}
公共类FooServiceImpl实现FooService接口{
...
}
VS
公共接口FooService接口{
无效doSmth();
}@Transactional(只读=真)
公共类FooServiceImpl实现FooService接口{
...
}
从<一个href=\"http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html\">http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html
Spring团队的建议是,你只标注具体的类与
@Transactional
注释,而不是注释界面。您当然可以在接口(或接口方法)关于@Transactional
注释,但是这是你,如果你使用的是基于接口的代理指望它只会工作。该注解的事实上没有继承的意思,如果你正在使用基于类的代理那么事务的设置将不能被基于类的代理基础设施的认可和对象不会被包裹在一个事务代理(这将是决定性的坏的)。因此,请接受Spring团队的建议,只标注具体的类(和混凝土类的方法)与@Transactional
注释。
的注:由于这个机制是基于代理的,只有'外部'方法调用通过代理未来将被拦截的这意味着'自我调用',即在目标中的方法对象调用目标对象的其他方法,在运行时不会导致实际交易,即使被调用的方法上都标有
@Transactional
!
块引用>(着重号的第一句话,从原来的其他重点。)
The question from the title in code:
@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 { ... }
解决方案From http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html
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.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屋!