user3813234
user3813234

Reputation: 1682

@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?

Upvotes: 37

Views: 19204

Answers (5)

Farrukh Ahmed
Farrukh Ahmed

Reputation: 493

When using spring data jpa you don't need to specify repository explicitly. The spring data jpa scans for all interfaces extending repository and generate implementation automatically.

Upvotes: 4

Rivalez
Rivalez

Reputation: 83

I would suggest as a good practice to annotate with @Repository class you are implementing for example:

@Repository
JpaRepositoryImpl implements JpaRepository 

Upvotes: 2

pvpkiran
pvpkiran

Reputation: 27048

It is not mandatory. The reason it will be working is beacause, you would have specified to framework the packages to look for repositories using @EnableJpaRepositories("packagestoscan")

Upvotes: 8

Tom
Tom

Reputation: 3850

I am gussing you set it up with @EnableJpaRepositories. This will scan for Spring Data repositories even if they are not annotated with @Repository.

From the javadoc:

Annotation to enable JPA repositories. Will scan the package of the annotated configuration class for Spring Data repositories by default.

You can also specify basePackages/basePackageClasses to change the default.

Upvotes: 4

Jesper
Jesper

Reputation: 206816

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.

Upvotes: 66

Related Questions