第一次开发REST应用程序,之前没有使用Spring Framework的经验。我开发的几乎所有网络应用都是用PHP(Laravel)、C#(ASP.NET和MVC)或Python(Django)编写的。
对于设计模式这个主题,我感到非常困惑。
在 https://spring.io/guides (https://spring.io/guides/tutorials/bookmarks/) 上提供的指南中,我看到一个设计模式是使用:
实体(Entity)、仓库(Repository)、服务(Service)和控制器(Controller)(RestController),例如:
当用户请求
对于设计模式这个主题,我感到非常困惑。
在 https://spring.io/guides (https://spring.io/guides/tutorials/bookmarks/) 上提供的指南中,我看到一个设计模式是使用:
实体(Entity)、仓库(Repository)、服务(Service)和控制器(Controller)(RestController),例如:
当用户请求
/user/{id}
(只是一个示例)时,Controller请求Service返回用户,因此Service会要求Repository返回一个Entity,然后Service将该Entity传递给Controller(至少在这个例子中)。request = Controller -> Service -> Repository -> Entity
response = Repository return Entity -> Service -> Controller
首先:
这个做法正确吗?我知道这样可以工作,但这是一种常见的做法(或至少是“最佳实践”)吗?
对我来说,将Entity
(如果此实体是数据库中对象的精确表示)传递给我的controller
似乎不正确。
假设我的实体具有密码属性。我正在将密码传递给我的controller
。当然,我可以在返回到controller
之前在service
上“隐藏”密码,但仍然会向controller
发送带有密码属性的entity
。
现在,反过来。假设我想创建一个新用户(Entity
),并且在我的数据库中,有一个根据注册日期自动计算的expirationDate
属性。我的Entity
表示必须具有expirationDate
属性,但在发布时,我不需要(也不应该)向此属性传递任何值。
在这种情况下的“最佳实践”是什么?在C# / MVC / ASP.NET中,通常我使用新的实体(称为ViewModel
)进行这些操作。
查看http://www.robertomarchetto.com/java_rest_api_best_practices_spring_boot,我看到另一种设计模式,并且似乎存在每种类型响应的Entity
(或DTO
)(例如我的示例中的UserResponseDto
和UserRegistrationDto
- DAO与Repository相同吗?)。
因此,在我的示例中使用此模式是否正确?
request -> Controller -> Service -> Repository -> Entity (DB representation)
response -> Repository return a Entity -> Service convert Entity to a DTO -> Controller