将一个 DAO 的方法用于另一个

Using methods of one DAO into another

我的应用程序中有 3 个服务 classes,每个服务都是为特定功能编写的,具有各自的 DAO 接口及其实现 classes。 所有服务都有不同的套餐。

说我有

AService.java & ADAO.java ADAO 接口注入 AService.java class。同样我有

BService.java & BDAO.java

CService.java & CDAO.java

现在我想参考AService.javaAService.java

中BDAO和CDAO实现的一些方法class

最好的方法是什么?

  1. 我在 AService.java 中注入了 BDAO 和 CDAO。那会是一个好习惯吗?在这种情况下,服务紧密耦合。

  2. 我把冗余代码写在各自的DAO中

  3. 我创建了一个通用的 DAO 并尝试从所有单独的 DAO 中提取所有常用方法并将其放入其中。这是一项广泛的任务。我也不确定将来哪个特定服务需要哪个 DAO 的哪个方法。

在这种情况下,我会选择第一个选项。服务可以具有比 DAO 更高的抽象级别。

当然我不会采用第二种方法,如果通用代码是一些实用程序代码,第三个选项可能有效,如果通用代码来自不同的代码,我不会这样做 entities/logical域名。

If you share behaviour in the DAO layer you should do it with inheritance or composition(Association) inside the DAO layer.

You sliced your application by Domains like "A", "B", "C", so the AService should not by pass the BService to access any kind of B's logic implemented in the B-Domain.

See @oliver-gierke talk "Whoops! Where did my architecture go?". Because of this easy Bypassing he proposes to organize packages like this

public      class com.product.a.AService
/*package*/ class com.product.a.ADao

public      class com.product.b.BService
/*package*/ class com.product.b.BDao

public      class com.product.c.CService
/*package*/ class com.product.c.CDao

With this you enforced that no other "Domain" is using the Daos of your Domain. Otherwise you can violate your Architecture rules.

The problem with sharing DAOs of different domains, is that you may bypass businesslogic implemented in the other domains service layer. For example, with every "delete" operation on B a email should be send to a customer. In case the AService uses the BRepository directly, it grants access to delete a B instance and bypass the logic to send an email.