javaspring-bootjparepository

@Repository not necessary when implementing 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.

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?


Solution

  • 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.

    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.