使用接口的原因是什么(Java EE 或 Spring 和 JPA) [英] what reasons are there to use interfaces (Java EE or Spring and JPA)

查看:20
本文介绍了使用接口的原因是什么(Java EE 或 Spring 和 JPA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数 J2EE(Spring 和 JPA)类都设计有接口.除了继承,还有什么技术原因吗?像动态代理或 AOP,我需要更多关于这个的技术细节

Most of the J2EE(Spring and JPA) classes are designed with interfaces. Except for inheritance, are there any technical reasons for this? Like dynamic proxy or AOP, I need more technical details about this

public interface UserDAO {
   void delete();
   void update();
   void save();
   List<User> get();
}

public class UserDAOImpl implements UserDAO {
   public void delete(){}
   public void update(){}
   public void save(){}
   public List<User> get(){}
}

推荐答案

主要有 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.

这篇关于使用接口的原因是什么(Java EE 或 Spring 和 JPA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆