java 如何使用spring的分层架构并仍然遵循面向对象的结构?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34429832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Layered architecture of spring and still follow object oriented structure?
提问by Nirbhay Mishra
I learned spring and its layered structure(controller,service and dao)
我学习了 spring 及其分层结构(控制器、服务和道)
@Controller("userController")
@service("userService")
@Transactional( propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = true)
@Repository("userDAO")
Now I am confused how do I make use of good OOPS practices(like this) with these layered structure to make a big project( real world have more complex business logic then sample applications usually provided). I also want to use these spring transaction and other features provided by framework. Can some please help me out with it or refer to open source project which clarifies my doubt.
现在我很困惑如何利用良好的 OOPS 实践(像这样)和这些分层结构来制作一个大项目(现实世界具有比通常提供的示例应用程序更复杂的业务逻辑)。我也想使用框架提供的这些spring事务和其他功能。有些人可以帮我解决这个问题或参考开源项目来澄清我的疑问。
回答by Faraj Farook
In nutshell
简而言之
Layered architecture will just ease the code maintainability and consistence when it becomes huge and complex.
当代码变得庞大和复杂时,分层架构只会简化代码的可维护性和一致性。
The fact to remember is that to do a proper software design before doing the implementation.
要记住的事实是,在执行之前先进行适当的软件设计。
- Encapsulation - Business logic specific for a domain model should go inside it.
- Abstraction - Segregate the interfaces according to the grouping of services while writing the common business logic in the abstraction.
- Inheritance - Use when you are drafting your domain objects
- Polymorphism - Along with inheritance when you want to change the business logic of child models.
- 封装 - 特定于域模型的业务逻辑应该在其中。
- 抽象 - 在抽象中编写公共业务逻辑时,根据服务分组分离接口。
- 继承 - 在您起草域对象时使用
- 多态性 - 当您想要更改子模型的业务逻辑时与继承一起使用。
In detail
详细
Below I'm trying my best to provide an example of an ERP application for this discussion. Hope an ERP is a sufficient big projectto view the business logic complexity.
下面我尽力提供一个 ERP 应用程序的例子来进行讨论。希望ERP是一个足够大的项目来查看业务逻辑的复杂性。
The below description is for any developer who need an idea to understand and make use of layered project structure in Spring (or any other framework).
以下描述适用于任何需要了解和使用 Spring(或任何其他框架)中的分层项目结构的开发人员。
But please note these are not rules to be followed but the best practices to be utilized. :)
但请注意,这些不是要遵循的规则,而是要使用的最佳实践。:)
1. Data Access Layer - Model /Domain Objects1. 数据访问层——模型/域对象
This contains the mapping of actual tables to classes.
这包含实际表到类的映射。
In an ERP example, this is where you get the models:
CustomerOrder
,CustomerOrderLine
This also contains the en-capsuled logic of child domain objects and the domain logic of self. For example, the
CustomerOrderLine
is a child ofCustomerOrder
. The child cannot exists without the parent. So the parent will have the full control of building the childs within it. ie Business logic encapsulation.. ie:Add CustomerOrderLine
,RemoveCustomerOrderLine
etc.. And when it comes to self domain logic,ApproveCustomerOrder
,RejectCustomerOrder
etc..
在ERP为例,这是你在哪里得到的模型:
CustomerOrder
,CustomerOrderLine
这也包含子域对象的封装逻辑和self的域逻辑。例如,
CustomerOrderLine
是 的孩子CustomerOrder
。没有父母,孩子就不能存在。因此,父级将完全控制在其中构建子级。即业务逻辑封装。. 即:Add CustomerOrderLine
,RemoveCustomerOrderLine
等等。而当谈到自己的域逻辑,ApproveCustomerOrder
,RejectCustomerOrder
等。
2. Data Access Layer - Repository2. 数据访问层——存储库
This contains nothing but simple CRUD to database with SELECT, INSERT, UPDATE and DELETE SQLs
. You can use repository pattern in Spring along with Spring Data JPA
.
这仅包含简单的 CRUD 到数据库SELECT, INSERT, UPDATE and DELETE SQLs
。您可以在 Spring 中使用存储库模式以及Spring Data JPA
.
Key note: do not write any complex logic in this layer unless your logic is highly data intensive
关键说明:不要在这一层写任何复杂的逻辑,除非你的逻辑是高度数据密集型的
In that case you might have to write one or more functions to do complex query statements. (Preferably in JPQL
)
在这种情况下,您可能需要编写一个或多个函数来执行复杂的查询语句。(最好在JPQL
)
In an ERP example, this is the place you write logic for
GetCustomerOrders
,GetCustomerOrderByCustomer
,GetCustomerOrderLines
,GetOrderByStatus
In simple terms this layer defines how the application will communicate with the outside entities such as Database.
在 ERP 示例中,这是您为
GetCustomerOrders
、GetCustomerOrderByCustomer
、GetCustomerOrderLines
、编写逻辑的地方GetOrderByStatus
简单来说,该层定义了应用程序将如何与外部实体(例如数据库)进行通信。
3. Service Layer
3. 服务层
This is the place where you should put your complex business logic which involved Multiple unconnected (not child - parent) domain models. These will be reused in Web Controllers and Rest API Controllers.
这是您应该放置涉及多个未连接(非子-父)域模型的复杂业务逻辑的地方。这些将在 Web 控制器和 Rest API 控制器中重用。
So to maintain the consistence and to implement the security, I would prefer all the business logic even which were written in the domain models gets wrapped up at this layer.
因此,为了保持一致性并实现安全性,我希望所有业务逻辑甚至是写在域模型中的业务逻辑都包含在这一层。
In the ERP exmple this is the place you write the logic or wrap the logic which is written in Domain Model. For example
CreateCustomerOrder
,ListCustomerOrder
,ApproveCustomerOrderLine
,ReleaseCustomerOrder
,...
在 ERP 示例中,这是您编写逻辑或包装在域模型中编写的逻辑的地方。例如
CreateCustomerOrder
,ListCustomerOrder
,ApproveCustomerOrderLine
,ReleaseCustomerOrder
,...
In case if these logic should get executed along with other model logics, then those should be called at sequence within service layer as well. For example.
如果这些逻辑应该与其他模型逻辑一起执行,那么这些逻辑也应该在服务层内按顺序调用。例如。
Misc Examples on complex business logic
复杂业务逻辑的杂项示例
If you want to create a
Purchase Order
for your supplier, when theCustomer Order
is released.
如果您想
Purchase Order
为您的供应商创建一个,则在Customer Order
发布时。
Then, this can be done by creating a service called SupplyChainService
binded using Spring AOP to the CustomerOrderService.ReleaseCustomerOrder
. In microservice design this can be done by a event published by Supply chain
domain microservice to a queue and get consumed by Customer Order
domain microservice
然后,这可以通过创建一个名为SupplyChainService
使用 Spring AOP 绑定到CustomerOrderService.ReleaseCustomerOrder
. 在微服务的设计,这可以通过发表一个事件来完成Supply chain
域的microService到队列并获得由消费Customer Order
领域的microService
4. Controllers
4. 控制器
Controllers can be categorized in two, namely: Web Controllers, and REST Controllers. No business logic should be implemented in this layer because the same logic can be required to call in Web as well as in API level.
控制器可以分为两类,即:Web 控制器和 REST 控制器。该层不应实现任何业务逻辑,因为在 Web 和 API 级别都可能需要调用相同的逻辑。
In the ERP system, this is the place where you will write the controller for your customer order form to enter data and save it to create a new customer order.
This will be the place you will also create a API controller like REST to create the customer order via a mobile application or from a windows client.
在 ERP 系统中,这是您为客户订单编写控制器以输入数据并保存数据以创建新客户订单的地方。
这将是您还将创建一个 API 控制器(如 REST)以通过移动应用程序或从 Windows 客户端创建客户订单的地方。
Thanks to the SO community who showed me areas that I didn't cover on OOP principles in this answer
感谢 SO 社区向我展示了我在此答案中未涉及 OOP 原则的领域
Edit
编辑
This is an answer when microservice is not too mainstream. Though it answered the OOP concepts, also look into CQRS based design as it's more common in modern micro service based architecture. Either way, you can incorporate OOP concepts regardless of what software architectural pattern you use.
当微服务不是太主流时,这是一个答案。虽然它回答了 OOP 概念,但也研究了基于 CQRS 的设计,因为它在现代基于微服务的架构中更为常见。无论哪种方式,您都可以合并 OOP 概念,而不管您使用什么软件架构模式。
回答by Marco Ferrari
Spring application design and OOD are not mutually exclusive.
Spring 应用程序设计和 OOD 并不相互排斥。
The typical Spring (MVC) application has the following structure:
典型的 Spring (MVC) 应用程序具有以下结构:
- One or more
@Controller
classes. These are the entry points of your application. They should not contain any business logic. Despite the name I identify them as the Vin MVC (Model-View-Controller) - One or more
@Service
classes. This is where you develop your business logic (BL). One of the benefit in putting your BL here is that it can be reused by multiple controllers (by a@Controller
and by a@RestController
for example). They are the Cin MVC. - One or more
@Repository
classes, where you implement your persistence layer (database, in-memory, whatever...). Additionally you can implement a set of@Component
s classes that describe your domain objects. These are the Min MVC. - Other classes that you can't map in the MVC pattern, like
@Configuration
,@ControllerAdvice
and other Spring configuration/management classes.
- 一节或多
@Controller
节课。这些是您的应用程序的入口点。它们不应包含任何业务逻辑。尽管名称我将它们标识为MVC 中的V(模型-视图-控制器) - 一节或多
@Service
节课。这是您开发业务逻辑 (BL) 的地方。将 BL 放在这里的好处之一是它可以被多个控制器(例如a@Controller
和 a@RestController
)重用。它们是MVC中的C。 - 一个或多个
@Repository
类,您可以在其中实现持久层(数据库、内存中,等等)。此外,您可以实现一组@Component
描述域对象的s 类。这些是MVC中的M。 - 其他类,你不能在MVC模式图,来样
@Configuration
,@ControllerAdvice
和其他Spring配置/管理类。
While designing each of these objects, you can follow whatever OODapproach you like.
在设计这些对象中的每一个时,您可以遵循您喜欢的任何OOD方法。
In the OOD example you mentioned, I would design my application like this:
在您提到的 OOD 示例中,我将这样设计我的应用程序:
- One view (
@Controller
) for each actor - One
@Service
for each use case - One
@Repository
and one@Component
for each domain class
@Controller
每个演员一个视图 ( )- 一个
@Service
为每个用例 - 一个
@Repository
和一个@Component
为每个域类
EDIT: you can find an example project I wrote for university here. It implements what I explained in the last three points with an additional layer (between @Controller and @Service) because there was a requirement to minimize dependencies on the Clayer. The concepts still apply.
编辑:您可以在此处找到我为大学编写的示例项目。它通过一个附加层(在@Controller 和@Service 之间)实现了我在最后三点中解释的内容,因为需要最大限度地减少对C层的依赖。这些概念仍然适用。
回答by Dima
I think, you are asking a wrong question here. Layered architecture is inherently not object-oriented, and therefore, while using (some of) the object-oriented practices with it would be possible or even advisable, it should not by itself be the goal. It is akin to asking how do I use best truck driving practices to ride a bike.
我想,你在这里问了一个错误的问题。分层架构本质上不是面向对象的,因此,虽然使用(一些)面向对象的实践是可能的,甚至是可取的,但它本身不应该是目标。这类似于询问我如何使用最佳卡车驾驶实践来骑自行车。
Why am I saying that layered architecture is not object oriented? Well, as we know, there are three principles that distinguish object-oriented design: encapsulation, inheritance and polymorphism.
为什么我说分层架构不是面向对象的?好吧,正如我们所知,区分面向对象设计的三个原则:封装、继承和多态。
While the last two may or may not be present, depending on your design choices, layered architecture is, pretty much, the oppositeof encapsulation: by nature of this approach, you explicitly separate your data ("DTOs") from your logic ("services").
虽然最后两个可能存在也可能不存在,这取决于您的设计选择,分层架构几乎与封装相反:根据这种方法的性质,您明确地将数据(“DTO”)与逻辑(“服务”)。
Don't get me wrong, the fact that this approach isn't object-oriented doesn't mean that there is anything wrong with it. And vice versa, "object-oriented" isn't synonymous with "good", it's one of many tools in a programmer's toolbox, and, as with any tool, is better suited to solving some problems than others.
不要误会我的意思,这种方法不是面向对象的这一事实并不意味着它有任何问题。反之亦然,“面向对象”并不是“好”的同义词,它是程序员工具箱中的众多工具之一,并且与任何工具一样,比其他工具更适合解决某些问题。
Layered architecture is a good design pattern, that can be successfully used to solve many real-life engineering problems. It has it's own set of best practices that can and should be used, and while that set may have some intersections with its counterpart from OOP, the two are certainly not equivalent.
分层架构是一种很好的设计模式,可以成功地用于解决许多现实生活中的工程问题。它有自己的一组可以而且应该使用的最佳实践,虽然该组可能与 OOP 中的对应物有一些交集,但两者肯定不是等价的。
回答by BValluri
You are trying to understand two different concepts that can interoperate together.
您正在尝试理解可以一起互操作的两个不同概念。
Layered Architecture
分层架构
Layer architecture is one of the architecture styles of the industry. In this we have separate layer to do specific logic. Example we have presentation layer, business layer and data service layer. This is called horizontal slicing of the application. There are other architectural styles like Service Oriented/Component based architecture where the application is sliced vertically.
层架构是业界的架构风格之一。在这个我们有单独的层来做特定的逻辑。例如我们有表示层、业务层和数据服务层。这称为应用程序的水平切片。还有其他架构风格,如面向服务/基于组件的架构,其中应用程序是垂直切片的。
Lets suppose you have automated reservation process. Normally if you go with the layered architecture design (horizontal slicing) then we have different layer to do the job required. But when it comes to the vertical slicing then we identify different entities of the application as Reservation, Customer Management, Fund Management. We will implement these components and they intercommunicate to build our reservation application. The point to remember here is internal component can fallow the same layered architecture.
假设您有自动预订流程。通常,如果您采用分层架构设计(水平切片),那么我们有不同的层来完成所需的工作。但是当涉及到垂直切片时,我们将应用程序的不同实体识别为预订、客户管理、资金管理。我们将实现这些组件,它们相互通信以构建我们的预订应用程序。这里要记住的一点是内部组件可以使用相同的分层架构。
OOPS Concepts
面向对象的概念
OOPS concepts helps you design the application in the object oriented manner. Once you identified the architecture style then you have to implemented the application in an extendable manner that can be easily maintained. So, they different implementation methodologies . OOPS is on of them. It suggest some of the design principles that helps you to implement the applications in a better way
OOPS 概念可帮助您以面向对象的方式设计应用程序。一旦确定了架构风格,就必须以易于维护的可扩展方式实现应用程序。因此,它们的实现方法不同。OOPS 就在其中。它提出了一些设计原则,可帮助您以更好的方式实施应用程序
See SOLID
见实体