java - REST API 调用是否应该在存储库层上使用 @Repository 进行?

标签 java spring-boot design-patterns

在我的实际项目中,我们遇到了一个难题,在我在其他公司的团队中,我们总是使用来自 SpringBoot 的 @Repository 进行 API 调用来检索存储库层上的数据,即使它们是一个简单的 RestTemplate getForEntity。但在这里我一如既往地做了,我们开始争论它是否应该位于存储库层(称为存储库),以及它是否需要 @Repository 注释并且可以仅使用 @Service 或 @Component。

就我个人而言,所有数据访问层操作都应该在存储库层上,即使它是 API 或数据库,只要它检索数据就应该在那里,我唯一怀疑的是使用 @Repository 因为这对于 Spring Data 自己的存储库来说更重要。

您认为 API 调用应该在存储库层还是在服务层?

最佳答案

来自the Javadoc of @Repository :

Indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects". Teams implementing traditional Java EE patterns such as "Data Access Object" may also apply this stereotype to DAO classes, though care should be taken to understand the distinction between Data Access Object and DDD-style repositories before doing so. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.

A class thus annotated is eligible for Spring DataAccessException translation when used in conjunction with a PersistenceExceptionTranslationPostProcessor. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tooling, aspects, etc.

As of Spring 2.5, this annotation also serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

如您所见,它并不是专门用于 Spring Data Repositories。

虽然 Spring Data 检测到 @Repository,但您也可以安全地将它们用于其他存储库,至少如果它用于数据访问的话。

关于java - REST API 调用是否应该在存储库层上使用 @Repository 进行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67191327/

相关文章:

java - 对于 Jhipster 生成的项目,H2 表未显示在 IntelliJ 中

.net - 创建自定义事件 - 对象发送者还是类型化发送者?

c# - 我们可以继承单例类吗?

java - 获取 PrintWriter 写入的文件

java - 在控制台中通过用户输入暂停线程时遇到困难

java - 如果我尝试在 jdk6 上使用我用 jdk7 编写的类,是否会遇到问题?

spring-boot - Liquibase 不使用 Spring Boot 获取种子数据

java - 使用 spring-boot-starter-integration 时找不到 org.springframework.integration.Message

java - 是否可以将特定信息放入界面中?

java - 设计模式: many objects of same type with multiple objects of other type