为什么要使用服务层? [英] Why use service layer?

查看:136
本文介绍了为什么要使用服务层?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 http://solitarygeek.com/java/developing-a-simple-java-application-with-spring/comment-page-1#comment-1639

在他提供的示例中,我试图弄清楚为什么首先需要服务层.如果您将其取出,那么在您的客户中,您可以这样做:

I'm trying to figure out why the service layer is needed in the first place in the example he provides. If you took it out, then in your client, you could just do:

UserDao userDao = new UserDaoImpl();
Iterator users = userDao.getUsers();
while (…) {
…
}

似乎服务层只是DAO的包装.有人可以给我一个情况,如果服务层被删除,情况可能会变得一团糟?我只是看不到拥有服务层的意义.

It seems like the service layer is simply a wrapper around the DAO. Can someone give me a case where things could get messy if the service layer were removed? I just don’t see the point in having the service layer to begin with.

推荐答案

让服务层成为DAO的包装是一种常见的反模式.在您提供的示例中,它肯定不是很有用.使用服务层意味着您将获得以下好处:

Having the service layer be a wrapper around the DAO is a common anti-pattern. In the example you give it is certainly not very useful. Using a service layer means you get several benefits:

  • 您将在控制器中最好完成的Web类型活动和与Web不相关的通用业务逻辑之间做出清晰的区分.您可以与控制器逻辑分开测试与服务相关的业务逻辑.

  • you get to make a clear distinction between web type activity best done in the controller and generic business logic that is not web-related. You can test service-related business logic separately from controller logic.

您可以指定事务行为,因此,如果您有多个数据访问对象的调用,则可以指定它们在同一事务中发生.在您的示例中,有一个对dao的初始调用,然后是一个循环,该循环可能包含更多的dao调用.将这些调用保留在一个事务中意味着数据库的工作量减少了(不必为每个对Dao的调用都创建一个新的事务),但是更重要的是,这意味着检索到的数据将更加一致.

you get to specify transaction behavior so if you have calls to multiple data access objects you can specify that they occur within the same transaction. In your example there's an initial call to a dao followed by a loop, which could presumably contain more dao calls. Keeping those calls within one transaction means that the database does less work (it doesn't have to create a new transaction for every call to a Dao) but more importantly it means the data retrieved is going to be more consistent.

您可以嵌套服务,以便如果一个服务具有不同的交易行为(需要自己的交易),您可以强制执行.

you can nest services so that if one has different transactional behavior (requires its own transaction) you can enforce that.

您可以使用postCommit拦截器执行通知之类的操作,例如发送电子邮件,这样不会浪费控制器.

you can use the postCommit interceptor to do notification stuff like sending emails, so that doesn't junk up the controller.

通常,我提供的服务包含单个用户类型的用例,该服务上的每个方法都是该用户将要执行的单个操作(在单个请求-响应周期中完成的工作),与您的例如,在那里通常不止有一个简单的数据访问对象调用.

Typically I have services that encompass use cases for a single type of user, each method on the service is a single action (work to be done in a single request-response cycle) that that user would be performing, and unlike your example there is typically more than a simple data access object call going on in there.

这篇关于为什么要使用服务层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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