@Transactional 应该放在哪里?在接口规范或实现中?
放置 @Transactional 注释的最佳实践是什么?我应该注释接口方法还是实现?
What is considered the best practice in placing the @Transactional
annotation? Should I annotate the interface method or the implementation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在我看来,这实际上完全取决于您的应用程序架构。这取决于您如何代理您的类。如果您的应用程序设置为
proxy-target-class='true'
(在您的应用程序上下文中),那么当您注释接口时,您的@Transactional
信息将不会被获取 ”查看 Spring 文档 -- 提示” 了解更多信息。
It really all depends on your application architecture, in my opinion. It depends on how you are proxying your classes. If you have your app set to
proxy-target-class='true'
(in your application context, then your@Transactional
information wont be picked up if you annotate the Interface.Check out The Spring Docs -- "Tips" for more information.
好问题。我一直把它放在实施中。也许是因为它是一个实现细节,而不是一个抽象。
您可能希望不同的实现具有不同的事务行为。
El Guapo 指出,除此之外,在界面上安装可能会出现更多与代理策略相关的问题。
Good question. I've always put it in the implementation. Perhaps because it is an implementation detail, rather than an abstraction.
You may want different implementations to have different transactional behaviours.
El Guapo noted that, in addition to that, there are more issues that can arise from putting on on the interface, related to the proxying strategy.
虽然事务管理在许多情况下是实现细节,但通常它也是接口细节。例如,在定义应用程序的服务接口时,您可能会考虑将 @Transactional 放入接口定义中,以明确说明您正在使用的传播策略。
While transactions management is implementation detail in many cases quite often it's an interface detail as well. For example, when defining interface of services of your application you might consider putting
@Transactional
into interface definition to specifically clarify what propagation strategy you're using.我没有在我的系统上使用接口,因为到目前为止我还没有真正看到是否可以在它上面实现任何东西。所以我在实现上添加了注释,我相信 Spring 会让一切对我来说都是正确的。
我不认为所有类都必须有接口。我看到很多有很多模式的架构,他们都喜欢界面。但有一个问题:如果您将 Spring 注释放入接口中,并且出于某种原因,您希望通过该接口使用另一种方法来完成实现类的事务,则您无法这样做。还是我错了?
干杯。
I don't use interfaces on my system because so far I don't really see if it will be possible to implement anything over it. So I put annotations on the implementation and I believe Spring would make everything correct to me.
I don't think that all classes must have interfaces. I see around lots of architectures with lots of patterns and they all love interfaces. But a question: if you put the Spring annotation into the interface and you, for some reason, you want another approach to the transaction of an implementation class done over this interface, you couldn't do that. Or am I wrong?
Cheers.