且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用接口的原因是什么(Java EE 或 Spring 和 JPA)

更新时间:2023-10-27 13:08:34

主要有 3 个原因,IMO:

There are 3 main reasons, IMO:

如果你向 Spring 请求 UserDAO 类型的 bean,它实际上会返回一个封装了实际 UserDAOImpl 实例的代理.这允许它划分事务、验证安全授权、记录访问、计算统计等.它可以在没有接口的情况下完成,但需要字节码操作.

If you ask Spring for the bean of type UserDAO, it will in fact return a proxy encapsulating the actual UserDAOImpl instance. This allows it to demarcate transactions, verify security authorization, log accesses, compute statistics, etc. It's possible to do it without an interface, but then byte-code manipulation is needed.

在对使用 UserDAO 的业务服务进行单元测试时,您通常会注入一个模拟 UserDAO 实现.再一次,当 UserDAO 是一个接口时,这更容易做到.使用具体类是可能的,但并非总是如此,使用接口仍然更容易

When unit-testing a business service which uses a UserDAO, you typically inject a mock UserDAO implementation. Once again, this is easier to do when UserDAO is an interface. It's possible with a concrete class, but it has not always been, and it's still easier with an interface

通过使用接口,您可以在一个地方为其客户定义 DAO 的真实合约.当然,它在具体实现中需要一个 setDataSource() 方法,但是客户端并不关心这个.他们所需要的只是 DAO 提供的一组数据访问方法.通过分离接口和具体实现,您可以确保客户端不依赖 DAO 的实现细节.

By using an interface, you have a place where you define the real contract of the DAO for its clients. Sure, it needs a setDataSource() method in the concrete implementation, but clients don't care about that. All they need is set of data-access methods offered by the DAO. By separating the interface and the concrete implementation, you make sure that the client doesn't rely on implementation details of the DAO.