繁体   English   中英

如果没有 @Repository 注释,代码可以正常工作,而使用注释也可以正常工作。 有什么区别?

[英]Without @Repository annotation the code works fine and with annotation also works fine. What is the difference?

我们可以用这种方式声明存储库类

public interface DepartmentRepository extends JpaRepository<Department, Integer>

这样

@Repository
public interface DepartmentRepository extends JpaRepository<Department, Integer>

提到的这两种方法有什么区别。 因为如果我们删除@Repository注释,那么代码将正常工作,那么有什么区别,谁能解释一下。

虽然其他答案 go 详细介绍了原型注释,但他们没有记录为什么不需要它,它是 Spring 引导功能 - 不是 Spring 框架。

使用 Spring Boot,它将自动从主 SpringBootApplication class 扫描子包,并使用SpringBootApplication的一部分自动配置为您检测存储库接口并创建 bean

Spring 数据存储库通常从 Repository 或 CrudRepository 接口扩展而来。 如果您使用自动配置,则从包含您的主要配置 class(使用 @EnableAutoConfiguration 或 @SpringBootApplication 注释的那个)的 package 开始搜索存储库。

https://docs.spring.io/autorepo/docs/spring-boot/current/reference/htmlsingle/#boot-features-spring-data-jpa-repositories

If you were not using Spring Boot, or the repository was not in package, or child-package, of the Spring Boot Application it would need to be annotated and the package scanned, or a bean created.

Spring 数据可以创建各种风格的@Repository 接口的实现。 Spring 引导为您处理所有这些,只要这些@Repositories 包含在您的@EnableAutoConfiguration ZA2F2ED4F8EBC2CBB4C21A29DC40AB61 的相同 package(或子包)中

对于许多应用程序,您只需将正确的 Spring 数据依赖项放在您的类路径上。 有一个用于 JPA 的 spring-boot-starter-data-jpa,用于 Mongodb 的 spring-boot-starter-data-mongodb 等。首先,创建一些存储库接口来处理您的 @Entity 对象。

Spring 引导尝试根据它找到的@EnableAutoConfiguration 猜测您的@Repository 定义的位置。 要获得更多控制,请使用 @EnableJpaRepositories 注释(来自 Spring Data JPA)。

有关此行为的更多信息,请参阅文档,例如对存储库的创建进行更多控制。

https://docs.spring.io/autorepo/docs/spring-boot/current/reference/htmlsingle/#howto-use-spring-data-repositories

取自 spring 文档:

@Repository 注释是任何满足存储库角色或原型的 class 的标记(也称为数据访问 Object 或 DAO)。 此标记的用途之一是异常的自动翻译,如异常翻译中所述。

它主要用作原型标记,但@Repository 是@Component 的特化,spring 用于类路径扫描。

https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-stereotype-annotations

https://www.journaldev.com/21460/spring-repository-annotation

@Repository注解用于表示 class 提供了对对象进行存储、检索、搜索、更新和删除操作的机制。

Spring Repositor y annotation 是@Component annotation 的一种特殊化,因此 Spring Repository 类由 spring 框架通过类路径扫描自动检测。

@Repository用于创建 Bean。 如果您没有使用此注解,那么您可以通过其他方式创建 bean,因此,它对您没有任何影响。

@Repository@Component的一种特殊类型,我们使用@Repository注释对充当存储库的接口进行注释。 @Repository处理捕获与数据持久性相关的异常。

我们在扩展JpaRepository时不需要使用@Repository注解,因为 Spring 检测到预定义的JpaRepository已扩展,并将扩展JpaRepository的接口识别为存储库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM