简体   繁体   English

如何分离存储库和服务层

[英]How to separate Repository and Service Layers

How should be separated Repository and Service? 应该如何分离存储库和服务? IMHO clients (eg Controller) should primaly use Service layer instead of Repository as it should be separated from persistance implementation. IMHO客户端(例如Controller)应该主要使用服务层而不是存储库,因为它应该与持久性实现分开。 Single Repository should provide methods of access of only one entity, while methods of Service are able to provide more complex actions, including usage of multiple repositories. 单一存储库应提供仅访问一个实体的方法,而服务方法能够提供更复杂的操作,包括使用多个存储库。

But what to do with rich repositories, that provides not only CRUD methods but much more, like JPARepository from Spring Data? 但是如何处理丰富的存储库,它不仅提供了CRUD方法,还提供了更多,比如Spring Data的JPARepository? In such implementations there are so many possible methods of fetching objects that duplicating them in Service isn't cool. 在这样的实现中,有很多可能的获取对象的方法,在Service中复制它们并不酷。

So what is the solution for that problem? 那么这个问题的解决方案是什么?

A. Duplicate methods in service layer like this A.像这样在服务层中重复方法

@Service
class XService{

   @Autowired
   private XRepository repository;

   public List<X> findAll(){
        return repository.findAll();
   }
}

B. Simply using repository in controllers (autowired or access method in service) B.只需在控制器中使用存储库(自动装配或服务中的访问方法)

C. Any other good approach? C.还有其他好方法吗?

Services should implement (business) logic and possibly modify entities according to that logic. 服务应该实现(业务)逻辑,并可能根据该逻辑修改实体。 If your service layer is only a thin wrapper around repositories, ie only fetching entities as your description suggests, something is wrong with your design. 如果您的服务层只是存储库的一个薄包装器,即只根据您的描述提示获取实体,那么您的设计就会出现问题。

Often logic is spread throughout the controllers. 逻辑通常遍布控制器。 Identify that logic, extract and encapsulate it in services and restrict Controllers to manage the application's flow, by orchestrating the appropriate services. 识别该逻辑,将其提取并封装在服务中,并通过编排适当的服务来限制控制器管理应用程序的流程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM