在分层架构中,通常有 3 层:application、domain 和 infrastructure。
基础设施
这里我放了repository的实现。在您的情况下,这是CrudRepository 的实现,我将直接在具体类中实现,而不使用中间接口。对于仓库中单个对象的行为,我们不做出任何假设,我们只是将它们放在那里并有效地检索它们。这样我们就没有领域的知识。我们只为域提供一个与之交互的接口:WarehouseRepository 的一组公共方法。
public class WarehouseRepository implements CrudRepository<Foo, Long> {
...
}
域
当您在 UnitOfWork/Transaction 中时,模型的各个部分与 WarehouseRepository 交互。在方法 adjustQuantityPlus 中,我们只看到应用程序不感兴趣并且不需要在基础架构级别知道的域逻辑。
public class SaleOrder {
public adjustQuantityPlus(LineItemID lineItemID,
WarehouseRepository warehouseRepository) {
this.lineItems.get(lineItemID).addOne(); //<-- add one to the order
Product product =
warehouseRepository.findByLineItem(lineItem);
product.minusOneFromStock(); //<-- decrease one from stock
}
}
应用
在这里,我们开始和停止操作许多域对象的事务 (UOWork)。每个业务方法对应一个业务用例。
public class CustomerEventsManager {
@Inject WarehouseRepository warehouseRepository;
@Inject SaleOrderRepository saleOrderRepository;
@Transactional
public wantsOneMoreOf(ProductID productID, SaleOrderID saleOrderID) {
SaleOrder saleOrder =
saleOrderRepository.findByID(saleOrderID)
saleOrder.adjustQuantityPlus(productToLineItem(productID),
warehouseRepository); //<-- add product
webPage.showPromoDiscount(); //<-- show promotional advertisement
}
}
以上代码是一笔交易,如果系统无法将产品添加到订单中,我不想给客户折扣。 adjustQuantityPlus 又是一个具有域逻辑的内部“事务”,对应用程序层隐藏。