没有@Repository批注,代码可以正常工作,带有批注的代码也可以正常工作。有什么区别?

时间:2020-06-30 11:25:47

标签: java spring spring-boot jpa spring-data-jpa

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

public interface DepartmentRepository extends JpaRepository<Department, Integer>

以这种方式

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

上述两种方法有什么区别。因为如果我们删除@Repository批注,那么代码可以正常工作,那么有什么区别,任何人都可以对此进行解释。

4 个答案:

答案 0 :(得分:3)

虽然其他答案都详细介绍了构造型注释,但它们并未记录为什么确实不需要构造型注释,而是Spring Boot功能-不是Spring Framework。

使用Spring Boot,它将自动扫描主SpringBootApplication类中的子软件包,并检测存储库接口,并使用SpringBootApplication

中的自动配置功能为您创建bean

Spring数据存储库通常从Repository或CrudRepository接口扩展。如果使用自动配置,则会从包含主配置类(用@EnableAutoConfiguration或@SpringBootApplication注释的主配置类)的包中搜索存储库。

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

如果您没有使用Spring Boot,或者存储库位于子程序包中,则需要对其进行注释并扫描该程序包,或者创建一个bean。

Spring Data可以创建各种形式的@Repository接口的实现。只要这些@Repositories包含在@EnableAutoConfiguration类的同一包(或子包)中,Spring Boot就会为您处理所有这些操作。

对于许多应用程序,所有您需要的是在类路径上放置正确的Spring Data依赖项。有一个用于JPA的spring-boot-starter-data-jpa,一个用于Mongodb的spring-boot-starter-data-mongodb等。要开始使用,请创建一些存储库接口来处理您的@Entity对象。

Spring Boot会根据发现的@EnableAutoConfiguration尝试猜测@Repository定义的位置。要获得更多控制权,请使用@EnableJpaRepositories批注(来自Spring Data JPA)。

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

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

答案 1 :(得分:1)

摘自Spring文档:

@Repository批注是实现存储库的角色或构造型(也称为数据访问对象或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

答案 2 :(得分:1)

@Repository注释用于指示该类提供了对对象进行存储,检索,搜索,更新和删除操作的机制。

Spring 存储库 y注释是 @Component 注释的特化,因此Spring框架通过类路径扫描自动检测Spring Repository类。 / p>

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

答案 3 :(得分:0)

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

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