本文介绍了有什么原因使用接口(Java EE或Spring和JPA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 大多数ј2ее(spring和JPA)类都设计有接口。 除继承之外,技术原因有哪些?像dynaimc代理或aop,我需要更多的技术细节这个 ex public interface UserDAO { void delete(); void update(); void save(); 列表<用户>得到(); } public class UserDAOImpl实现UserDAO { public void delete(){} public void update(){} public void save() {} public List< User> get(){} } 解决方案是三个主要原因,IMO: 第一个原因:代理。 如果你问Spring键入UserDAO,它实际上将返回一个封装实际UserDAOImpl实例的代理。这样就可以对事务进行划分,验证安全授权,日志访问,计算统计信息等。可以在没有接口的情况下进行操作,但需要进行字节码操作。 第二个原因:可测试性。 当对使用UserDAO的业务服务进行单元测试时,通常会注入一个模拟的UserDAO实现。再次,当UserDAO是一个界面时,这更容易做到。有可能是一个具体的类,但它并不总是,并且它更容易一个接口 第三个原因:解耦。 通过使用界面,您可以在其中为其客户定义DAO的真实合同的位置。当然,在具体实现中需要一个 setDataSource()方法,但是客户端并不在意。他们所需要的是DAO提供的数据访问方法。通过分隔接口和具体实现,您确保客户端不依赖DAO的实现细节。 Most of ј2ее(spring and JPA) classes are designed with interfaces. except inheritance any technical reasons are there ?? like dynaimc proxy or aop ,i need more technical details about this expublic 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(){}} 解决方案 There are 3 main reasons, IMO:First reason: proxies.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.Second reasons: testability.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 interfaceThird reason: decoupling.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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-11 18:08