問題描述
代碼中標題的問題:
@Transactional (readonly = true)
public interface FooService {
void doSmth ();
}
public class FooServiceImpl implements FooService {
...
}
對
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 注釋放在哪里:在接口定義或實現類中?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!