在我的实际项目中,我们遇到了一个难题,在我在其他公司的团队中,我们总是使用来自 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/