简体   繁体   English

Spring Autowire - 接口和实现需要DAO类吗?

[英]Spring Autowire - Interface and Implementation DAO Class needed?

First off, I have done some reading and I am wondering what is the purpose of having a Interface and the implementation class for example the Data Access Objects (DAO)? 首先,我做了一些阅读,我想知道有一个接口和实现类的目的是什么,例如数据访问对象(DAO)? I have read that it increases flexibility, but I was wondering if someone could provide a concrete example as to why we need an interface. 我已经读到它增加了灵活性,但我想知道是否有人可以提供一个具体的例子来说明为什么我们需要一个接口。

If we are autowiring, do we still need to use a Interface and Implementation that implement the interface? 如果我们是自动装配,我们是否仍然需要使用实现该接口的接口和实现? If so, why? 如果是这样,为什么? Do we just need the impl? 我们只需要impl吗?

Thank you in advance. 先感谢您。

You don't strictly need an interface. 你并不需要严格的接口。 But there are two reasons to prefer them: 但是有两个理由喜欢它们:

  • You can easily swap the implementation for testing purposes 您可以轻松交换实现以进行测试
  • Proxy-ing beans for the purposes of aspect oriented programming or similar is easier (Java supports it out of the box) 用于面向方面编程或类似的代理bean更容易(Java支持开箱即用)

Other reasons might be added, but these are the main 2 in my opinion. 可能会增加其他原因,但在我看来,这些是主要的2。 Still, don't feel forced to work like that. 不过,不要觉得被迫这样工作。 If the case you're working on does not warrant this flexibility, there's no need to complicate things. 如果您正在处理的案例不能保证这种灵活性,则无需复杂化。

And, by all means, never call your classes *Impl . 而且,无论如何, 永远不要打电话给你的班级* Impl If you can not come up with a proper name for the implementation, it means you shouldn't be having an interface to begin with. 如果您无法为实现提供正确的名称,则意味着您不应该有一个开头的界面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM