实现 JpaRepository 时不需要@Repository? [英] @Repository not necessary when implementing JpaRepository?
问题描述
我的 Spring Boot 应用程序中有一个存储库类.首先,我用 @Repository
注释它,然后我实现了 JpaRepository
.现在我去掉了注释,它仍然有效.
I have a repository class in my spring boot app. First, I annotated it with @Repository
and then I implemented JpaRepository
. Now I got rid of the annotation and it still works.
我看到 JpaRepository
有 @NoRepositoryBean
注释.
I saw that JpaRepository
has the @NoRepositoryBean
annotation.
这是如何工作的?或者这不应该起作用并且我的应用程序中发生了一些奇怪的事情?
How does this work? Or should this not work and there's something weird going on in my application?
推荐答案
扩展JpaRepository
的接口确实没必要放@Repository
注解;Spring 通过扩展预定义的 Repository
接口之一来识别存储库.
It is indeed not necessary to put the @Repository
annotation on interfaces that extend JpaRepository
; Spring recognises the repositories by the fact that they extend one of the predefined Repository
interfaces.
@NoRepositoryBean
注释的目的是防止 Spring 将该特定接口本身视为存储库.JpaRepository
接口有这个注解,因为它本身不是一个存储库,它意味着由你自己的存储库接口扩展,而那些是应该选择的.
The purpose of the @NoRepositoryBean
annotation is to prevent Spring from treating that specific interface as a repository by itself. The JpaRepository
interface has this annotation because it isn't a repository itself, it's meant to be extended by your own repository interfaces, and those are the ones that should be picked up.
或者这不应该起作用并且我的应用程序中发生了一些奇怪的事情?
Or should this not work and there's something weird going on in my application?
它可以正常工作,您的应用程序中没有任何奇怪的事情发生.
It works as it should and there is nothing weird going on in your application.
这篇关于实现 JpaRepository 时不需要@Repository?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!