我真的需要服务层吗? [英] Do I really need a service layer?

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

问题描述

我的Web应用程序是使用Spring MVC + Hibernate编写的。

My web application is written using Spring MVC + Hibernate.


  • 我的模型是客户实体POJO。

  • 我有一个DAO对象CustomerDAO,它的方法saveCustomer(c)包含与Hibernate交互的代码;

  • 然后我创建了一个 CustomerService ,带有saveCustomer(c)方法,只需将客户对象传递给dao进行保存;

  • 最后有CustomerController和客户.jsp,谁负责视图层,jsp的表单字段绑定到控制器端的Customer对象。控制器调用服务。

  • My model is "Customer" entity POJO.
  • I have got a DAO object "CustomerDAO", its method "saveCustomer(c)" contains the code interacting with Hibernate;
  • Then I created a "CustomerService with a "saveCustomer(c)" method who simply pass the customer object to the dao for saving;
  • Finally there are "CustomerController" and customer.jsp, who are responsible for the view layer, the jsp's form fields are bound to a Customer object on the controller side. The controller calls the service.

我看到很多应用程序遵循这个(最佳)实践,但我想知道为什么我需要一个服务层。

I saw a lot of applications follow this (best) practice but I'm wondering why I would need a service layer.

也许它对于解耦很有用目的:我可以向控制器显示通用外观并注入服务HibernateDAO,GaeDAO,MyDAO等等......但是我也可以在没有服务的情况下执行此操作:使用接口。

Maybe it's useful for decoupling purpose: I can show a universal facade to the controllers and inject into the service HibernateDAO, GaeDAO, MyDAO, and so on.... But I could do that without the service, too: using an interface.

我也考虑过:验证。我会在服务中进行客户验证,但....在Spring控制器中验证更方便。

I also tought: validation. I'll make my Customer validation in the service but.... it's much more convenient to validate in Spring controller.

请帮助我理解这个概念:)

Help me understand the concept please :)

推荐答案

你不要'需要服务层。但是它可以帮助您

You don't need a service layer. However it helps you to


  • 解耦您的组件

  • 您可以在服务中强制执行特定的业务规则应该与存储库无关的层

  • 让服务外观一个或多个存储库。让我们考虑以下示例

class Service {
  private DatabaseBarRepo barRepo;
  private DatabaseFooRepo fooRepo;

  @Transactional
  public void serviceRoutine() {
     barRepo.doStuff();
     fooRepo.doStuff();
  }
}

这里我们让两个单独的存储库参与相同的事务。这是特定于数据库的,尽管这些原则对其他系统也是有效的。

Here we let two separate repositories take part in the same transaction. This is specific for databases albeit the principles are valid for other systems as well.

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

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